How can I open an url in a webview
or in the default browser after clicking a button? Currently, when I click the btn1
button it prompts me to select a browser from the phone. I want to open this url inside the default browser or in a webview
.
Here is my java code:
public class myactivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt1 = (Button) findViewById(R.id.btn_click_login);
btn_login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://google.com"));
startActivity(myWebLink);
}
}
);
}
Here you go.
Make sure to include <uses-permission android:name="android.permission.INTERNET"/>
in manifest
Intent internetIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
internetIntent.setComponent(new ComponentName("com.android.browser","com.android.browser.BrowserActivity"));
internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(internetIntent);
can try this your intent
intent.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
in your code
public void onClick(View v) {
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
myWebLink.setData(Uri.parse("http://google.com"));
startActivity(myWebLink);
}
In android there are two types of intents:
Explicit Intents: where target component is specified, explicitly.
Implicit Intents: Target Component is not specified, instead there are some other fields are provided, which are Data, Action, Category.. and according to these fields(attributes) android system filters activities or components to handle the intent.
And you are using Implicit Intent, and it will list all the activities which can work on Action_VIEW, and specified URI. To avoid this situation you have only option that you can restrict Android system to filter further, by some other parameter, or changing it to Explicit Intent. and To Change it to Explicit Intent you would need target component Name.
put a WebView in your layout xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/web"
/>
</RelativeLayout>
Get a reference to it in your activity
WebView mWeb = (WebView) findViewById(R.id.web);
call loadUrl() on it.
mWeb.loadUrl("http://google.com");