Android与JavaScript的交互,以实现从WebView中打开原生页面并传递参数

发布于:2024-06-30 ⋅ 阅读:(147) ⋅ 点赞:(0)

在Android应用中,实现Android与JavaScript的交互,以实现从WebView中打开原生页面并传递参数,可以通过以下详细步骤完成:

1. 准备工作

  • 添加WebView至布局:在你的Activity或Fragment的XML布局文件中加入WebView控件。

2. 配置WebView

  • 启用JavaScript:在Java代码中设置WebView的属性,启用JavaScript支持。
WebView webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
  • 添加JavaScriptInterface:创建一个Java类作为桥梁,供JavaScript调用,用来打开原生页面。

3. 创建JavaScriptInterface

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void openNativePage(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        mContext.startActivity(intent);
    }
}

确保在AndroidManifest.xml中注册所有可能被启动的Activity。

4. 注册URL Scheme

在目标Activity的AndroidManifest.xml中,通过Intent Filter注册自定义URL Scheme。

<activity android:name=".NativeActivity">
    <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="myapp" android:host="native" />
    </intent-filter>
</activity>
5. 交互逻辑
  • 在WebView中嵌入JavaScript:在网页中编写JavaScript代码,通过调用WebAppInterface中的方法来打开原生页面。
<button onclick="openNativePage('myapp://native?key=value')">打开原生页面</button>
<script>
    function openNativePage(url) {
        window.Android.openNativePage(url);
    }
</script>
  • 传递参数:通过URL的查询参数(如?key=value)来传递数据。
6. 接收参数

在被启动的原生Activity中,通过Intent获取传递的参数。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_your_layout);

    // 获取Intent
    Intent intent = getIntent();
    if (intent != null && intent.getData() != null) {
        // 解析Intent中的Uri
        Uri data = intent.getData();
        
        // 从Uri中获取"key"参数的值
        String Key = data.getQueryParameter("key");
        
        // 使用codeValue进行后续操作
        if (Key != null) {
            Log.d("Key ", "key: " + Key );
            // 进行你需要的操作,比如显示在TextView上,或者作为请求参数等
        } else {
            Log.w("Key ", "key parameter was not found in the Intent's Uri.");
        }
    } else {
        Log.e("Intent Error", "Intent or Intent Data is null.");
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到