0

How do I get and share the current URL in webview? My share works but doesn't share the current URL loaded.

Here is my code in WebView

private String mTrackUrlChange;

private WebViewClient webViewClient = new WebViewClient(){

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        frameLayout.setVisibility(View.VISIBLE);
        mTrackUrlChange=url;
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

       mTrackUrlChange = url;
    }
};

For my share:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu, menu);
    MenuItem shareItem = menu.findItem(R.id.action_share);
    ShareActionProvider mShare = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, mTrackUrlChange);
    mShare.setShareIntent(shareIntent);
    shareIntent.putExtra(Intent.EXTRA_STREAM, mTrackUrlChange);
    mShare.setShareIntent(shareIntent);
    return super.onCreateOptionsMenu(menu);

}
kielou
  • 437
  • 3
  • 18

1 Answers1

0

My share works but doesn't share the current URL loaded

You have not explained what that means. However, your code has some problems that may contribute to whatever your problem is.

First, you are building the Intent and calling setShareIntent() too soon. mTrackUrlChange will be null in onCreateOptionsMenu(), because your WebView will barely have begun loading the Web page. Build the Intent and call setShareIntent() inside onPageFinished(), not inside onCreateOptionsMenu().

Beyond that, since you are setting EXTRA_STREAM, the extra needs to be a Uri, not a String, and the MIME type needs to be the MIME type of the actual content (e.g., text/html for a Web page). Also, you are calling setShareIntent() multiple times, which is not necessary.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I mean it works but when when I use share, it doesn't contain the URL – kielou Feb 17 '17 at 18:17
  • 1
    @kielou: Please see the second paragraph of my answer. – CommonsWare Feb 17 '17 at 18:20
  • it doesn't allow me to call `setShareIntent()` inside `onPageFinished()` – kielou Feb 17 '17 at 18:34
  • @kielou: Why not? You will need to make some other changes, such as making `mShare` be a field, rather than a local variable inside of `onCreateOptionsMenu()`. [Here is a sample app](https://github.com/commonsguy/cw-omnibus/tree/v8.3/ActionBar/ShareNative) demonstrating calling `setShareIntent()` from places other than `onCreateOptionsMenu()`. – CommonsWare Feb 17 '17 at 18:38