loddard
loddard

Reputation: 17

how to open external links in webview

I've created my simple browser app, and when i click on a link for example in whatsapp, android asks what browser should open that, and I select my browser but it doesn't open that link, instead just goes to homescreen. what should I do?

I have added this in manifest:

   <category android:name="android.intent.category.DEFAULT" />
   <data android:scheme="http" />
   <data android:scheme="https" />

And I guess I need to add this code: Uri url = getIntent().getData(); webview1.loadUrl(url.toString());

but I don't know where to paste it, I tried it onCreate but failed.

Upvotes: 0

Views: 2192

Answers (2)

udit7395
udit7395

Reputation: 626

You should load the url from which you get the intent in OnResume() method. Please have a look at the code below.

private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    webView = findViewById(R.id.external_url_content);
    webView.getSettings().setJavaScriptEnabled(true);
}

@Override
protected void onResume() {
    super.onResume();
    Uri url = getIntent().getData();
    if (url != null) {
        Log.d("TAG", "URL Foud");
        Log.d("TAG", "Url is :" + url);
        webView.loadUrl(url.toString());
    }
}

Also the intent-filters in manifest are as follows

<activity android:name=".MainActivity">
     <intent-filter>
         <action android:name="android.intent.action.MAIN"/>
         <category android:name="android.intent.category.LAUNCHER"/>
     </intent-filter>

     <intent-filter>
         <action android:name="android.intent.action.SEND"/>
         <category android:name="android.intent.category.DEFAULT"/>
         <data android:mimeType="text/plain"/>
     </intent-filter>

     <intent-filter>
         <action android:name="android.intent.action.VIEW"/>
         <category android:name="android.intent.category.DEFAULT"/>
         <category android:name="android.intent.category.BROWSABLE"/>
         <data android:scheme="http"/>
         <data android:scheme="https"/>
     </intent-filter>
</activity>

You can find more about Lifecycle Activity over here

Upvotes: 2

Sreejesh K Nair
Sreejesh K Nair

Reputation: 603

use WebView In your layout

<WebView
    android:id="@+id/external_url_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

In your activity

WebView browser;

You can use this inside onCreate or functions based on your needs

browser = (WebView) findViewById(R.id.external_url_content);
browser.getSettings().setJavaScriptEnabled(true);
String url_path="https://stackoverflow.com/questions/48473930/how-to-open-external-links-in-webviewsid"
browser.loadUrl(url_path);

Upvotes: 0

Related Questions