Javascript函数不接收Android-Java值

Javascript function won't receive Android-Java value

本文关键字:Android-Java 函数 Javascript      更新时间:2023-09-26

我似乎不能把我的思想围绕Android-Java发送值到Javascript在我的webview。没有错误,只是不能工作。我第一次运行的sharedprefs存储测试工作得很好,只是将结果传递给Javascript失败了。我试过其他方法,但都失败了。我花了将近一个月的时间在这上面,在这里搜索和阅读了很多。

我应该使用布尔值以外的东西吗?我假设当Javascript获得结果时,它将是字符串格式。

一定是我做错了什么。我需要更改/添加/删除什么才能使其工作?

一些我的AndroidManifest.xml:

<uses-sdk
android:minSdkVersion="1"
android:targetSdkVersion="17" />

My MainActivity.java file:

public class MainActivity extends Activity {
private WebView wView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wView = (WebView) findViewById(R.id.wView);
wView.getSettings().setJavaScriptEnabled(true);
wView.getSettings().setRenderPriority(RenderPriority.HIGH);
wView.addJavascriptInterface(new Check(this), "Flex"); // firstRunCheck
wView.loadUrl("file:///android_asset/www/index.html");

我的Check.java文件,它存储了我想要的布尔值,在sharedprefs:

public class Check extends MainActivity {
Context rContext;
Check(Context d){
 rContext = d;
}
@JavascriptInterface
public void firstRunCheck(String key){
Boolean firstRunCheck = getSharedPreferences("PREFS", MODE_PRIVATE).getBoolean("firstRunCheck", true);
if (firstRunCheck) {
showAlert();  // this is a call to the showAlert() method.
getSharedPreferences("PREFS", MODE_PRIVATE).edit() 
.putBoolean("firstRunCheck", false).commit();
return;
}
}
}

应该得到Java结果的Javascript函数:

Function FirstRunTest(){
var Result = Flex.firstRunCheck()
TextBox1.value = Result
}

返回void。您需要更改Check.java文件中的方法定义以返回一个值。

试题:

public boolean firstRunCheck(){
  Boolean firstRunCheck = getSharedPreferences("PREFS", MODE_PRIVATE).getBoolean("firstRunCheck", true);
  if (firstRunCheck) {
    showAlert();  // this is a call to the showAlert() method.
    getSharedPreferences("PREFS", MODE_PRIVATE).edit() 
    .putBoolean("firstRunCheck", false).commit();
  }
  return firstRunCheck;
}

在Javascript,假设Flex。firstRunCheck返回boolean:

Function FirstRunTest(){
  var Result = Flex.firstRunCheck();
  TextBox1.value = if(Result) ? "True" : "False";
}