使用webview javascriptInterface在Android 4.2.2中运行的应用程序在Android 2.3.3中无效。
它有targetSdkVersion =“19”
和Build属性为4.2
我创建了2.3.3的模拟器和设备3.7“WVGA。
OnCreate Here -
@JavascriptInterface
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vWebview = (WebView) findViewById(R.id.vWebview);
btnView = (Button) findViewById(R.id.btnView);
txtView = (TextView) findViewById(R.id.txtView);
vWebview.setWebChromeClient(new WebChromeClient());
vWebview.setWebViewClient(new WebViewClient());
try {
if ("2.3".equals(Build.VERSION.RELEASE)) {
javascriptInterfaceBroken = true;
}
} catch (Exception e) {
// Ignore, and assume user javascript interface is working correctly.
}
// Add javascript interface only if it's not broken
if (!javascriptInterfaceBroken) {
vWebview.addJavascriptInterface(new JScriptInterface(),
"AndroidFunction");
}
WebSettings websetting = vWebview.getSettings();
websetting.setJavaScriptEnabled(true);
Log.d("Main", "Called");
vWebview.loadUrl("file:///android_asset/sample.html");
btnView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//vWebview.loadUrl("javascript:showAndroidToast('Hello')");
try{
runOnUiThread(new Runnable() {
@Override
public void run() {
vWebview.loadUrl("javascript:showAndroidToast('Hello')");
}
});
}
catch(Exception ee){
Log.d("Exception", "Called" + ee.toString());
}
}
});
}
JsInterface -
public class JScriptInterface {
public JScriptInterface() {
// TODO Auto-generated constructor stub
}
public void showToast(String toast) {
try{
Log.d("JS", "Called" + toast);
// txtView.setText(toast);
Toast.makeText(MainActivity.this, toast, Toast.LENGTH_LONG).show();
}
catch(Exception ee){
Toast.makeText(MainActivity.this, ee.toString(), Toast.LENGTH_LONG).show();
}
}
}
答案 0 :(得分:2)
我想你可能碰到了this known issue。以下是解决问题的方法:Handling Android 2.3 WebView’s broken AddJavascriptInterface
的信用将来,请考虑更详细地描述您的问题。 "哪个不起作用"我不知道这个问题,所以我只是用Google搜索" javascriptinterface 2.3.3" - 再说一次,你可以自己完成。
<强> UPD 强>
您需要将解决方法中的方法作为覆盖到WebViewClient
。
对于您的代码,它看起来应该是这样的:
vWebview.setWebChromeClient(new WebChromeClient());
try {
if ("2.3".equals(Build.VERSION.RELEASE)) {
javascriptInterfaceBroken = true;
}
} catch (Exception e) {
// Ignore, and assume user javascript interface is working correctly.
}
// Add javascript interface only if it's not broken
if (!javascriptInterfaceBroken) {
vWebview.addJavascriptInterface(new JScriptInterface(),
"AndroidFunction");
}
if (!javaScriptInterfaceBroken) vWebview.setWebViewClient(new WebViewClient());
else {
vWebview.setWebViewClient(new WebViewClient() {
// And here you put the code from the article
@Override
public void onPageFinished(WebView view, String url) { ... }
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { ... }
});
}
答案 1 :(得分:0)
请检查设备而不是模拟器。当我在Android 2.3.6中检查时,它运行良好。不幸的是我没有得到任何与我们的模拟器相同的2.3.3设备。如果有人有设备,请检查并确认我。非常感谢您的宝贵意见。