1

我试图显示一个没有连接的自定义错误,但它在下面不起作用的是代码,并且在 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);
    }
}
4

1 回答 1

1

为什么在没有连接的情况下完成活动?

让吐司像:

Toast.makeText(getApplicationContext(),"Network is down",
                        Toast.LENGTH_SHORT).show();

然后让视图显示某种按钮来“重试”网络请求,无论如何我都会这样做。Toast 当前未显示可能是因为活动在 Toast 之后立即关闭,因此没有足够的时间显示它

于 2012-02-06T22:56:47.797 回答