美文网首页
安卓广播机制

安卓广播机制

作者: 水固态中 | 来源:发表于2017-11-30 18:59 被阅读0次

    标准广播

    有序广播

    接收系统广播

    1.动态注册监听网络变化

    public class MainActivity extends Activity
    {  private IntentFilter intentFilter;
        private NetworkChangeReceiver networkChangeReceiver;
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    //实例化意图过滤器
    intentFilter=new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
    //实例化广播接收器
    networkChangeReceiver=new NetworkChangeReceiver();
    //注册绑定
    registerReceiver(networkChangeReceiver,intentFilter);
        }
    @Override
    protected void onDestroy()
    {
    // TODO: Implement this method
    super.onDestroy();
    //解绑
    unregisterReceiver(networkChangeReceiver);
    }
    class NetworkChangeReceiver extends BroadcastReceiver
    {
    @Override
    public void onReceive(Context context, Intent intent)
    {
    // TODO: Implement this method
    Toast.makeText(context,"网络变化",Toast.LENGTH_SHORT).show();
    }
    }
    }

    进一步优化

    @Override
      public void onReceive(Context context, Intent intent)
      {
      // 找到系统管理网络服务类
      ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(context.CONNECTIVITY_SERVICE);
      //得到网络信息实例
      NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
      if(networkInfo!=null&&networkInfo.isAvailable()){
        Toast.makeText(context,"网络可联通",Toast.LENGTH_SHORT).show();
      }else{
        Toast.makeText(context,"无网络",Toast.LENGTH_SHORT).show();
      }
      }

    记得添加权限哦

    相关文章

      网友评论

          本文标题:安卓广播机制

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