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

在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.");
    }
}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值