【发布时间】:2014-08-28 12:16:02
【问题描述】:
我正在尝试设置一个简单的 Android 应用程序,该应用程序显示一个 web 视图并通过 Javascript 接口提供一些额外的功能。
我正在运行 Kitkat(通过 Cyanogenmod)的 HTC One S 上进行测试。当我检查 webview 插入的对象(Android)是空的“对象 {}”。我无法通过加载的页面使用界面中的功能。
我已经构建了一个更复杂的活动,但无法使界面正常工作,因此我创建了这个新应用程序进行测试,其中仅包含 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);
}
}
WebApp接口
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 检查 web 视图,如果我调用 Android 或 window.Android,我会得到一个空的反对返回“Object {}”。或者如果我尝试使用上面接口中定义的方法,我会收到一个方法未定义的错误。
【问题讨论】:
-
有什么问题? showToast 不工作?你是从js文件中调用的吗?
-
我已经编辑了问题,并提供了有关该问题的更多信息,谢谢
标签: javascript android webview android-4.4-kitkat