有序广播
package com.example.broadcast;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import com.example.broadcast.util.DateUtil;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private CheckBox ckStop;
private TextView tvOrder;
private final static String TAG = "MainActivity";
private final static String ORDER_ACTION = "com.example.broadcast.order";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ckStop = findViewById(R.id.ck_stop);
tvOrder = findViewById(R.id.tv_order);
findViewById(R.id.bt_send).setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.bt_send) {
tvOrder.setText("");
Intent intent = new Intent(ORDER_ACTION);
sendOrderedBroadcast(intent,null);
}
}
@Override
protected void onStart() {
super.onStart();
//优先级越大的接收器越早接受到广播
//优先级相同的接收器,先注册的先接收到广播
orderAReceiver = new OrderAReceiver(); // 创建一个有序广播的接收器A
// 创建一个意图过滤器A,只处理ORDER_ACTION的广播
IntentFilter filterA = new IntentFilter(ORDER_ACTION);
filterA.setPriority(12); // 设置过滤器A的优先级,数值越大优先级越高
registerReceiver(orderAReceiver, filterA); // 注册接收器A,注册之后才能正常接收广播
orderBReceiver = new OrderBReceiver(); // 创建一个有序广播的接收器B
// 创建一个意图过滤器B,只处理ORDER_ACTION的广播
IntentFilter filterB = new IntentFilter(ORDER_ACTION);
filterB.setPriority(8); // 设置过滤器B的优先级,数值越大优先级越高
registerReceiver(orderBReceiver, filterB); // 注册接收器B,注册之后才能正常接收广播
orderDReceiver = new OrderDReceiver(); // 创建一个有序广播的接收器D
// 创建一个意图过滤器D,只处理ORDER_ACTION的广播
IntentFilter filterD = new IntentFilter(ORDER_ACTION);
filterD.setPriority(6); // 设置过滤器D的优先级,数值越大优先级越高
registerReceiver(orderDReceiver, filterD)