我正在尝试创建一个简单的Android应用程序,该应用程序显示一个Webview并通过Javascript接口提供一些额外的功能。
我正在使用运行Kitkat(通过Cyanogenmod)的HTC One S进行测试。当我检查Webview时,插入的对象(Android)为空“Object {}”。我无法通过加载的页面使用接口中的函数。
我曾经构建过一个更复杂的活动,但无法使接口正常工作,因此我创建了这个新的测试应用程序,其中只包含来自Webview指南的代码。仍然无法将方法插入到公开对象中。
我的活动
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://47e148ba.ngrok.com");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
WebAppInterface
import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
/**
* Created by graeme on 28/08/2014.
*/
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
布局
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.mydomain.jswebview"
minSdkVersion 17
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
您可以看到我正在使用方法所需的装饰器,这似乎是大多数问题的解决方案。如果有预设值,则可能会干扰我的Android Studio开发?编辑:在JS文件中或者通过Chrome检查Webview时,在调用Android或window.Android时,我会得到返回的空对象“Object {}”。或者如果我尝试使用上面定义的方法,我会收到未定义的方法错误。