当我的服务器中只有一个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
文件进行重定向操作时,突然,WebView
小部件消失,默认浏览器应用程序在屏幕上打开,结果我无法在我的设备屏幕上看到echo '<script> Android.showToast("Welcome") </script>';
,也无法在WebView
小部件上看到。
我成功解决了我的问题。我只是实现了web客户端,并将其设置在loadUrl
之前。
browser.setWebViewClient(new WebViewClient());