龙港哪里有做百度网站的,网站设计服务平台,企业所得税怎么算公式,苏州做网站推广在Android应用中#xff0c;实现Android与JavaScript的交互#xff0c;以实现从WebView中打开原生页面并传递参数#xff0c;可以通过以下详细步骤完成#xff1a;
1. 准备工作
添加WebView至布局#xff1a;在你的Activity或Fragment的XML布局文件中加入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;}JavascriptInterfacepublic 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.NativeActivityintent-filteraction android:nameandroid.intent.action.VIEW /category android:nameandroid.intent.category.DEFAULT /category android:nameandroid.intent.category.BROWSABLE /data android:schememyapp android:hostnative //intent-filter
/activity5. 交互逻辑
在WebView中嵌入JavaScript在网页中编写JavaScript代码通过调用WebAppInterface中的方法来打开原生页面。
button onclickopenNativePage(myapp://native?keyvalue)打开原生页面/button
scriptfunction openNativePage(url) {window.Android.openNativePage(url);}
/script传递参数通过URL的查询参数如?keyvalue来传递数据。
6. 接收参数
在被启动的原生Activity中通过Intent获取传递的参数。
Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_your_layout);// 获取IntentIntent intent getIntent();if (intent ! null intent.getData() ! null) {// 解析Intent中的UriUri 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 Intents Uri.);}} else {Log.e(Intent Error, Intent or Intent Data is null.);}
}