首页 > 其他分享 >发送有序广播

发送有序广播

时间:2022-08-20 15:16:19浏览次数:40  
标签:anotherFilter IntentFilter 发送 广播 有序 new import android myBroadcastReceiver

只需要在上文发送标准广播的基础上增加一个广播接收器,我取名为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);
    }
}

标签:anotherFilter,IntentFilter,发送,广播,有序,new,import,android,myBroadcastReceiver
From: https://www.cnblogs.com/jarico/p/16607730.html

相关文章