广播监听网络变化

来源:互联网 发布:字符串压缩算法 编辑:程序博客网 时间:2024/05/16 08:54
<receiver android:name=".BroadcastReceiver.Recevice" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
</receiver>


------------------------------------------------
XML文件注册 wifi 移动 开启 关闭会自动调用
或者动态注册

------------------------------------------------
public class Recevice extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo Info=connectivityManager.getActiveNetworkInfo();


        if(Info==null){
            Toast.makeText(context,"断开连接",Toast.LENGTH_SHORT).show();
        }else{
            if(Info.getType()==0){
                Toast.makeText(context,"连接移动数据",Toast.LENGTH_SHORT).show();
            }
            if(Info.getType()==1){
                Toast.makeText(context,"连接wifi",Toast.LENGTH_SHORT).show();
            }
        }
    }


}
-----------------------------------------------------
状态码 0 移动  1 wifi  断开为null 
0 0
原创粉丝点击