我想创建一个app.if数据连接,然后自动显示toast。否则不显示。 我创建了很多应用程序,但我不知道如何做到这一点。 我试试这个但不行。
公共类MainActivity扩展了Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.wv);
if(CheckNetwork.isInternetAvailable(MainActivity.this))
{
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
// webView = (WebView) findViewById(R.id.wv);
// webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
MainActivity.this.setProgress(progress * 1000);
}
});
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(MainActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl("http://slashdot.org/");
}
else{
//no connection
Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG);
toast.show();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else
{
finish();
}
return super.onKeyDown(keyCode, event);
}
}
答案 0 :(得分:1)
以下是可以通过互联网访问的代码:
//===================== INTERNET CHECK===========
public boolean isConnectingToInternet(Context context) {
boolean connected = false;
ConnectivityManager CManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NInfo = CManager.getActiveNetworkInfo();
if (NInfo != null && NInfo.isConnectedOrConnecting()) {
try {
if (InetAddress.getByName("www.rameshkhatri.com").isReachable(7000)) { // you change to your website name
// host reachable
connected = true;
} else {
connected = true;
// connected = false;
// host not reachable
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
但是你在AsyncTask中检查了互联网连接,因为网络调用不会在UIThread上,否则你会得到异常。 希望这可以帮助。随时询问您是否有疑问