发送有序广播

只需要在另一篇文章基础上增加一个广播接收器,这个新增的广播接收器我取名为AnotherBroadcastReceiver
然后修改MainActivity中的代码

package com.example.demoapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private BroadcastReceiver myBroadcastReceiver,
            anotherBroadcastReceiver;

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

        Button btnSendBroadcast = findViewById(R.id.btn_send_broadcast);
        btnSendBroadcast.setOnClickListener(this);

        myBroadcastReceiver = new MyBroadcastReceiver();
        anotherBroadcastReceiver = new AnotherBroadcastReceiver();

        IntentFilter myFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myFilter.addAction("com.example.demoapplication.MY_BROADCAST");

        IntentFilter anotherFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        anotherFilter.addAction("com.example.demoapplication.MY_BROADCAST");
        anotherFilter.setPriority(100);

        this.registerReceiver(myBroadcastReceiver, myFilter);
        this.registerReceiver(anotherBroadcastReceiver, anotherFilter);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_send_broadcast) {
            Intent intent = new Intent("com.example.demoapplication.MY_BROADCAST");
//            sendBroadcast(intent);
            sendOrderedBroadcast(intent, null); //发送有序广播
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
        unregisterReceiver(anotherBroadcastReceiver);
    }
}
posted @ 2022-08-20 14:57  jarico  阅读(43)  评论(0)    收藏  举报