public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeRexeiver networkChangeRexeiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter=new IntentFilter(); //"android.net.conn.CONNECTIVITY_CHANGE":当网络变化时,系统发出的值为"android.net.conn.CONNECTIVITY_CHANGE"的广播 intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeRexeiver=new NetworkChangeRexeiver(); registerReceiver(networkChangeRexeiver,intentFilter); } @Override protected void onDestroy() { super.onDestroy(); //取消注册 unregisterReceiver(networkChangeRexeiver); } class NetworkChangeRexeiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //ConnectivityManager系统服务类,专门用于管理网络连接的 ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo(); if (networkInfo!=null&&networkInfo.isAvailable()){ Toast.makeText(context,"network is available",Toast.LENGTH_LONG).show(); }else { Toast.makeText(context,"network is unavailable",Toast.LENGTH_LONG).show(); } } } }
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Android 网络状态变更的广播
最新推荐文章于 2024-08-18 03:01:04 发布