android 广播监听网络状态

1.自定义网络状态工具类

package com.screening.uitls;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;

public class NetWorkUtils {
    //没有连接网络
    private static final int NETWORK_NONE=-1;
    //移动网络
    private static final int NETWORK_MOBILE=0;
    //无线网络
    private static final int NETWORK_WIFI=1;
    public static int getNetWorkState(Context context){
        //得到连接管理器对象
        ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        if(networkInfo!=null&&networkInfo.isConnected()){
            if(networkInfo.getType()==ConnectivityManager.TYPE_WIFI){
                return NETWORK_WIFI;
            }else if(networkInfo.getType()==ConnectivityManager.TYPE_MOBILE){
                return NETWORK_MOBILE;
            }
        }else {
            return NETWORK_NONE;
        }
        return NETWORK_NONE;
    }
}

2.定义基类BaseActivity,在这个类中注册网络状态监听广播

package com.activity;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;

import com.screening.uitls.NetWorkReceiver;

/**
 * Created by gyl1 on 12/21/16.
 */

public class BaseActivity extends AppCompatActivity {
    Context context;
    private boolean isRegistered = false;
    private NetWorkReceiver netWorkChangReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        context = this;
        //注册网络状态监听广播
        netWorkChangReceiver = new NetWorkReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkChangReceiver, filter);
        isRegistered = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解绑
        if (isRegistered) {
            unregisterReceiver(netWorkChangReceiver);
        }
    }
}

3.其他类直接继承基类,这样每个页面都可以监听到网络状态的变化,注意需要申请网络权限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />


你可能感兴趣的:(android 广播监听网络状态)