使用下面的工作代码::
public class Android_Activity extends Activity {
private Android_Activity _activity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
_activity = this;
setContentView(R.layout.main);
mwebview=(WebView)view.findViewById(R.id.webview);
mwebview.getSettings().setJavaScriptEnabled(true);
mwebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
if(checkInternetConnection(_activity)==true){
if(savedInstanceState==null)
mwebview.loadUrl("http://abc.com");
else
mwebview.restoreState(savedInstanceState);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(_activity);
builder.setMessage("Please check your network connection.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
mwebview.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
if(mwebview.getVisibility()==View.VISIBLE)
{
_activity.setProgress(progress * 100);
}
}
});
mwebview.setWebViewClient(new HelloWebViewClient());
}
//HelloWebViewClient class for webview
private class HelloWebViewClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
view.loadUrl(url);
return true;
}
} //HelloWebViewClient-class
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && mwebview.canGoBack() ){
mwebview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//To check whether network connection is available on device or not
public static boolean checkInternetConnection(Activity _activity) {
ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
return true;
else
return false;
}//checkInternetConnection()
}
而且在你的 main.xml 布局中,你必须有一个 id 为 webview 的 webview