android - 增加网络检控的页面

访问量: 79

1. 在main activity (例如,包含了4个tab页的主要Activity) 中,增加 :

    final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    IntentFilter intentFilter;
    NetWorkStateReceiver receiver;


    private void watchNetwork() {
        if (intentFilter == null) {
            intentFilter = new IntentFilter();
            intentFilter.addAction(CONNECTIVITY_ACTION);
            receiver = new NetWorkStateReceiver();
            receiver.setOnNetworkChange(new NetWorkStateReceiver.OnNetworkChange() {
                @Override
                public void onNetworkChange(boolean hasNetwork) {
                    if (!hasNetwork) {
                        startActivity(new Intent(MainActivity.this, NoNetworkActivity.class));
                    }
                }
            });
        }
        registerReceiver(receiver, intentFilter);
    }

2. 创建对应的network receiver 

public class NetWorkStateReceiver extends BroadcastReceiver {

    OnNetworkChange onNetworkChange;


    @Override
    public void onReceive(Context context, Intent intent) {
        if (onNetworkChange != null) {
            onNetworkChange.onNetworkChange(isNetworkAvailable(context));
        }
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
//                    Toast.makeText(context, "网络打开", Toast.LENGTH_SHORT).show();
                    Log.d("== Network", "network enable");
                    return true;
                }
            }
        }
//        Toast.makeText(context, "网络关闭", Toast.LENGTH_SHORT).show();
        Log.d("== Network", "network disable");
        return false;
    }

    public void setOnNetworkChange(OnNetworkChange onNetworkChange) {
        this.onNetworkChange = onNetworkChange;
    }

    public interface OnNetworkChange {
        void onNetworkChange(boolean hasNetwork);
    }
}

订阅/RSS Feed

Subscribe

分类/category