我正在使用此代碼使用HTML按鈕調用Android Activity。但它不適合我。我只想從我的html頁面點擊按鈕時調用我的Android活動「echos.class」。在JavaScript Webview中調用意圖
我JavaScriptInterface類
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast) {
Intent mainIntent = new Intent(mContext, echos.class);
JavaScriptInterface.this.startActivity(mainIntent);
}
private void startActivity(Intent mainIntent) {
// TODO Auto-generated method stub
}
}
我的WebView類
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.web1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
myWebView.loadUrl("file:///android_asset/www/index.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
我的HTML頁面
<html>
<head>
</head>
<body>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
</body>
</html>
你的方法startActivity是空的。開始活動mContext.startActivity(mainIntent); – Pasha