我正在尝试显示无连接的自定义错误,但下面的代码无效 在manifest.xml中我提供了网络状态。 Connection()正在检查类中的网络状态。希望这有助于解决问题。
package com.testing.webview;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final int DIALOG_NONETWORK = 0;
WebView mWebView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(!Connection()){
Context context = getApplicationContext();
CharSequence text = "Sorry you need an Internet connection! Please try again when the network is available.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
finish();
}
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/index.html");
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.setBackgroundColor(Color.TRANSPARENT);
}
public boolean Connection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()){
return true;
}
else{
return false;
}
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
答案 0 :(得分:1)
为什么在没有连接后完成活动?
祝吐像:
Toast.makeText(getApplicationContext(),"Network is down",
Toast.LENGTH_SHORT).show();
然后让视图显示某种按钮来“重试”网络请求,这就是我要做的事情。 Toast目前没有显示,因为活动在吐司后立即关闭,所以没有足够的时间来展示它