【发布时间】:2015-08-24 06:42:35
【问题描述】:
当我的服务器中只有一个php 文件时,以下代码运行良好。结果,当服务器响应 android 时,WebView 小部件在屏幕上处于稳定状态。首先,请查看我的代码是否正确:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//WebView Object
WebView browser;
browser = (WebView) findViewById(R.id.webView);
//Enable Javascript
browser.getSettings().setJavaScriptEnabled(true);
//Inject WebAppInterface methods into Web page by having Interface name 'Android'
browser.addJavascriptInterface(new WebAppInterface(this), "Android");
//Load URL inside WebView
String s = "http://127.0.0.1:8080/apps/webview.php";
browser.loadUrl(s);
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/**
* Show Toast Message
* @param toast
*/
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}
现在,请查看以下php 代码是否正确:
<?php
echo "hello";
echo '<script> Android.showToast("Hello") </script>';
?>
当我运行上述代码时,WebView 小部件在屏幕上处于稳定状态,我可以在屏幕上使用Toast 看到Hello 文本。
当我把php上面的代码改成如下时问题就开始了:
<?php
echo "hello";
header("Location:welcom.php");
?>
然后我添加另一个php代码,它的名字是welcome,如下:
<?php
echo '<script> Android.showToast("Welcome") </script>';
?>
现在,当我在我的设备中运行代码时,首先,当它对welcome.php 文件执行重定向操作时,突然,WebViewwidget 消失了,默认浏览器应用程序在屏幕上打开,结果我在设备屏幕和WebView 小部件上都看不到echo '<script> Android.showToast("Welcome") </script>';。
【问题讨论】: