重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
Android 动态注册监听网络变化实例详解
桃源网站建设公司创新互联,桃源网站设计制作,有大型网站制作公司丰富经验。已为桃源上1000家提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的桃源做网站的公司定做!新建一个BroadcastTest项目,然后修改MainActivity中的代码,如下:
public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter=new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //广播接收器想要监听什么广播,就在这里添加相应的action networkChangeReceiver=new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver,intentFilter); //调用resigerReceiver()方法进行注册 } @Override protected void onDestroy(){ super.onDestroy(); unregisterReceiver(networkChangeReceiver); } class NetworkChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ // Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show(); ConnectivityManager connectionManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); //得到系统服务类 NetworkInfo networkInfo=connectionManager.getActiveNetworkInfo(); if(networkInfo!=null&&networkInfo.isAvailable()){ Toast.makeText(context,"network is available",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context,"network is unavailable",Toast.LENGTH_SHORT).show(); } } } }