广播接收器-BroadcastReceiver

广播可以分为标准广播有序广播
标准广播:一种完全异步执行的广播,当广播发出后,几乎所有的广播接收器都能同时接受到广播,无法被截断。
有序广播:一种同步执行的广播,广播发出去之后,同一时间只会有一个广播接收器接收到广播,当这个广播接收器里面的逻辑处理完以后,广播才会继续处理。所以有序广播可以被截断。

注册广播:广播的注册可以分为两类。静态注册动态注册。静态注册是在androidManifest.XML里注册,动态注册需要在代码里注册。

动态注册广播(registerRecervice())

那么如何创建一个广播接收器呢?只需要创建一个类继承BroadcastReceiver,之后重写BroadcastReceiver里的onReceiver()方法。当广播到来后,onReceiver()方法就会的到执行,具体的逻辑会在onReceiver()里执行。

public class MainActivity extends AppCompatActivity {

    private NetWorkChangeBroadcast netWorkChangeBroadcast;

    @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");

        netWorkChangeBroadcast = new NetWorkChangeBroadcast();

        registerReceiver(netWorkChangeBroadcast, intentFilter);

    }

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

    private class NetWorkChangeBroadcast extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
               Toast.makeText(context, "Net work is available", Toast.LENGTH_SHORT).show();
        }
    }
}

  1. 首先注册一个广播接收器:创建一个类NetWorkChangeBroadcast继承BroadcastReceiver,重写onReceiver()方法。
  2. 然后准备注册广播接收器:
    registerReceiver(BroadCastReceiver receiver, IntentFilter filter);
    因为注册广播registerReceiver()方法需要传递两个参数。
    因此我们需要在onCreate()方法里初始化NetWorkChangeBroadcast以及创建IntentFilter对象,
    在intentFilter增加一个action。原因是当系统发送的广播与action里的android.net.conn.CONNECTIVITY_CHANGE相同时,广播接收器将接收广播,并在onReceiver()方法里处理具体的逻辑。
    之后注册registerReceiver(netWorkChangeBroadcast, intentFilter);
    动态注册的广播广播接收器一定要销毁,因此我们在ondestroy()方法里注销
    unregisterReceiver(netWorkChangeBroadcast);

现在把onReceiver()方法里的逻辑写的更详细一些:

@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, "Net work is available", Toast.LENGTH_SHORT).show();
     }else {
          Toast.makeText(context, "Network is unavailable", Toast.LENGTH_SHORT).show();
     }
 }

getSystemService(Context.CONNECTIVITY_SERVICE);得到连接服务,返回一个ConnectivityManager对象。
connectivityManager.getActiveNetworkInfo();得到活动的网络信息,返回一个NetworkInfo(网络信息)对象。
判断networkInfo是否为空和网络是否可用。
** 访问系统的网络状态需要添加权限,在AndroidManifest.xml添加权限

静态注册广播

File - New - Other - Broadcast Receiver 。之后系统会为我们创建一个广播接收器(一个类继承BroadcaReceiver并重写了onReceiver()),并且在AndroidManifest.xml注册:

    
    

Exported表示这个广播接收器是否允许接受本程序以外的广播,Enabled表示是否启用这个广播接收器。

在里面添加action

    
        
            
        
    

发送自定义的广播:

    Intent intent = new Intent(action);
    sendBroadcast(intent);

发送有序广播

    Intent intent = new Intent(action);
    sendOrderedBroadcast(intent, null);

sendOrderedBroadcast()接受两个参数,第一个Intent,第二个与权限有关的字符串,这里写null就行。

阻断有序广播
需要在onReceiver()方法中添加abortBroadcast();方法

本地广播

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private NetWorkChangeBroadcast netWorkChangeBroadcast;
    private LocalBroadcastManager localBroadcastManager;
    private Button send;

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

        netWorkChangeBroadcast = new NetWorkChangeBroadcast();
        intentFilter = new IntentFilter();
        intentFilter.addAction(action);

        localBroadcastManager = LocalBroadcastManager.getInstance(this);//获取实例
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送广播
                Intent intent = new Intent(action);
                localBroadcastManager.sendBroadcast(intent);
            }
        });

        //注册广播
        localBroadcastManager.registerReceiver(netWorkChangeBroadcast, intentFilter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销广播        
      localBroadcastManager.unregisterReceiver(netWorkChangeBroadcast);
    }

    private class NetWorkChangeBroadcast extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "Net work is available", Toast.LENGTH_SHORT).show();    
        }
    }

}

你可能感兴趣的:(广播接收器-BroadcastReceiver)