美文网首页Android开发经验谈
Android 监听网络状态更改的广播(静态注册)

Android 监听网络状态更改的广播(静态注册)

作者: 24K纯帅豆 | 来源:发表于2015-08-22 19:36 被阅读4159次

    1、定义一个类,假设为StateBroadcastReceiver继承BroadcastReceiver,然后重写onReceive方法:

    @Override

    public voidonReceive(Context context, Intent intent) {

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    State wifiState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();//获取wifi网络状态

    State mobileState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();//获取移动数据网络状态

    //没有执行return,则说明当前无网络连接

    if(wifiState != State.CONNECTED&& mobileState != State.CONNECTED) {

    System.out.println("------------> Network is validate");

    intent.setClass(context, NetWorkErrorActivity.class);

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(intent);

    return;

    }

    //判断网络是否已经连接

    System.out.println("------------> Network is ok");

    }

    2、在Manifest文件中注册广播

    <receiver android:name=".StateBroadcastReceiver" >

          <intent-filter>

                android:name="android.net.conn.CONNECTIVITY_CHANGE" />

          </intent-filter>

    </receiver>

    3、别忘了加权限

    相关文章

      网友评论

        本文标题:Android 监听网络状态更改的广播(静态注册)

        本文链接:https://www.haomeiwen.com/subject/eomoqttx.html