Android SDK WebView call Activity

2019-01-09 01:44发布

I'm trying to launch an Activity when clicking a link inside a WebView component.

My Webview is loaded inside Main.java and I would like to launch SubActivity.java when clicking a link inside the Website which is in Main.java?

Also, how can I pass parameters to this activity?

Example: inspection://Project/1

"Inspection" is the name of my application, inspection is the Activity I would like to launch and 1 is the ID I would like to have.

3条回答
一夜七次
2楼-- · 2019-01-09 02:24

First Add javascript method on your webpage's button onclick() The function defined below..

function showAndroidToast(toast) {
    AndroidFunction.showToast(toast);
}

Android Code is here for javascript Interface..

public class MyJavaScriptInterface {
    Context mContext;
     private Activity activity;

        public MyJavaScriptInterface(Activity activiy) {
            this.activity = activiy;
        }
 @JavascriptInterface
    public void showToast(String toast){
  Intent i=new Intent(getApplicationContext(), Subactivity.class);

  i.putExtra("data", "tosecondActivity");
 startActivity(i);

}

查看更多
Fickle 薄情
3楼-- · 2019-01-09 02:37

One option is to override the URL loading of the web view and pick up the click you want to launch the new activity. Check out the use of a subclassed WebViewClient in the docs:

http://developer.android.com/resources/tutorials/views/hello-webview.html

Another option is to bind your activity to a custom URL scheme. It's pretty common in doing client side OAuth, frequently through the browser instead of a WebView, but it should work similarly enough. There's a full example here:

https://github.com/brione/Brion-Learns-OAuth

Which shows how to bind the url scheme handler as well as handling getting launched via the Intent it generates (see onResume() in OAUTH.java).

查看更多
祖国的老花朵
4楼-- · 2019-01-09 02:44

You could use WebView's addJavaScriptInterface to allow JavaScript to control your application (in this case, to allow JavaScript to fire an Intent when a link is clicked).

To do this you need to pass a class instance to bind to JavaScript, this could be something like the following:

private final class JsInterface {
      public void launchIntent(final String payload) {
         Activity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
               // use the payload if you want, attach as an extra, switch destination, etc.
               Activity.this.startActivity(new Intent(Activity.this, SomeOtherActivity.class));
            }
         });
      }
   }

Then you add that to the WebView with something along these lines:

webView.addJavascriptInterface(js, "Android");

Then in JavaScript from the WebView you just use your new "Android" object's "launchIntent" method.

查看更多
登录 后发表回答