Android动态监测网络状态变化

最近小伙伴遇到一个问题。公司的APP中需要程序随时注意网络状态的变化,一旦变化就要弹框提醒,这可愁坏了他,于是让我帮忙找一下相关的方法。这里我就贴出来对应的方法供大家使用,同时也作为自己的一份记录。

  • 获取当前网络状态,这个我们也可以单独使用,比如做某个操作的时候需要判断网络状态
public class NetworkUtil {
    public static final int TYPE_NONE = -1;
    public static final int TYPE_MOBILE = 0;
    public static final int TYPE_WIFI = 1;

    private NetworkUtil() {}

    /**
     * 获取网络状态
     *
     * @param context
     * @return one of TYPE_NONE, TYPE_MOBILE, TYPE_WIFI
     * @permission android.permission.ACCESS_NETWORK_STATE
     */
    public static final int getNetWorkStates(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
            return TYPE_NONE;//没网
        }
        int type = activeNetworkInfo.getType();
        switch (type) {
            case ConnectivityManager.TYPE_MOBILE:
                return TYPE_MOBILE;//移动数据
            case ConnectivityManager.TYPE_WIFI:
                return TYPE_WIFI;//WIFI
            default:
                break;
        }
        return TYPE_NONE;
    }
}
  • Activity中广播动态注册
public class MainActivity extends BaseActivity{

    private MyBRReceiver myReceiver;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        //核心部分代码:
        myReceiver = new MyBRReceiver();
        //添加广播过滤器确定接收什么广播
        IntentFilter itFilter = new IntentFilter();
        itFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        //注册广播
        registerReceiver(myReceiver, itFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除广播
        unregisterReceiver(myReceiver);
    }
}
  • 广播接收者
public class MyBRReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        int netWorkStates = NetworkUtil.getNetWorkStates(context);
        switch (netWorkStates) {
            case NetworkUtil.TYPE_NONE:
                Toast.makeText(context,"断网了",Toast.LENGTH_SHORT).show();
                break;
            case NetworkUtil.TYPE_MOBILE:
                Toast.makeText(context,"打开了移动网络",Toast.LENGTH_SHORT).show();//打开了移动网络
                break;
            case NetworkUtil.TYPE_WIFI:
                //打开了WIFI
                Toast.makeText(context,"打开了WIFI",Toast.LENGTH_SHORT).show();//打开了移动网络
                break;
            default:
                break;
        }
    }
}

通过该方法我们就能利用广播动态监测网络的变化。 

你可能感兴趣的:(Android基础)