BroadcastReceiver广播监听android网络状态

用BroadcastReceiver广播监听判断android手机网络状态。

一、新建Receiver类继承BroadcastReceiver

public class ConnectReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if(networkInfo!=null && networkInfo.getType()== ConnectivityManager.TYPE_WIFI){
            Toast.makeText(context,"now is wifi",Toast.LENGTH_SHORT).show();
        }
        else if(networkInfo!=null && networkInfo.getType()== ConnectivityManager.TYPE_MOBILE){
            Toast.makeText(context,"now is 移动数据",Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(context,"没有网络",Toast.LENGTH_SHORT).show();
        }
    }
}

二、AndroidMainfest.xml静态注册Receiver类,注意添加网络权限

    

    
        
    

三、监听处理,注意在onDestroy()里取消广播接收器的注册

public class MainActivity extends AppCompatActivity {

    private ConnectReceiver connectReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        connectReceiver = new ConnectReceiver();
        registerReceiver(connectReceiver,intentFilter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(connectReceiver);
        super.onDestroy();
    }
}

 

你可能感兴趣的:(Android)