IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android 广播实例汇总-普通广播 有序广播及静态注册、动态注册详解附源码讲解 -> 正文阅读

[移动开发]Android 广播实例汇总-普通广播 有序广播及静态注册、动态注册详解附源码讲解

Android广播实例汇总

先看看效果:
在这里插入图片描述

一、普通广播

在这里分别讲解广播的静态注册和动态注册,有需要源码的可以留言~

静态注册广播

静态注册广播的基本概念及注意事项:
manifest里注册receiver
app未运行时,可以收到广播
静态注册有一些严格的限制:
1、只允许静态注册监听一些指定的系统广播。
2、支持监听一些指定的packageName的自定义广播。
注册方式:
1、自定义一个Receiver类,复写onReceiver方法。
2、在manifest里添加一个receiver,在intent-filter标签里添加感兴趣的广播。

下面是静态注册所需的文件:(以红色框标注)
在这里插入图片描述
Mainactivity 是主界面,可以选择动态注册还是静态注册。
Staticactivity 是静态注册的发送
StaticReceiver 是静态注册的接收
Commonclass 是公共类,静态注册和动态注册都需要用到

MainActivity–主界面

package com.xtc.broadcastalldemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btn_sta,btn_dyn,btn_ord;

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

        btn_sta = (Button) findViewById(R.id.btn_static_registration);
        btn_dyn = (Button) findViewById(R.id.btn_dynamic_registration);
        btn_ord = (Button) findViewById(R.id.btn_ordered_registration);
        btn_sta.setOnClickListener(mOnClickListener);
        btn_dyn.setOnClickListener(mOnClickListener);
        btn_ord.setOnClickListener(mOnClickListener);
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            Intent intent = null;
            switch (id) {
                case R.id.btn_static_registration:
                    intent = new Intent(MainActivity.this,StaticActivity.class);
                    break;
                case R.id.btn_dynamic_registration:
                    intent = new Intent(MainActivity.this,DynamicActivity.class);
                    break;
                case R.id.btn_ordered_registration:
                    intent = new Intent(MainActivity.this,OrderlyActivity.class);
                    break;

            }
            startActivity(intent);
        }
    };
}

activity_main.xml–主界面布局文件

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/title_bar"
            android:layout_marginTop="5dp"
            android:textSize="20sp"
            android:gravity="center"
            android:text="广播案例汇总"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/title_bar_ordinary"
            android:layout_marginTop="8dp"
            android:textSize="16sp"
            android:gravity="center"
            android:text="一、普通广播"/>

        <Button
            android:id="@+id/btn_static_registration"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="1.静态注册"/>

        <Button
            android:id="@+id/btn_dynamic_registration"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="2.动态注册"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/title_bar_ordinary"
            android:layout_marginTop="8dp"
            android:textSize="16sp"
            android:gravity="center"
            android:text="二、有序广播"/>

        <Button
            android:id="@+id/btn_ordered_registration"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="动态注册"/>

    </LinearLayout>
</ScrollView>

StaticActivity–静态注册

package com.xtc.broadcastalldemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
//静态注册广播实例
public class StaticActivity extends AppCompatActivity {

    private Button btn_send_one,btn_send_two,btn_send_three;
    private static final String TAG = "fancy";
    private String action1 = "one";
    private String action2 = "two";
    private String key1 = "first";
    private String key2= "second";
    private String key3= "third";


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

        btn_send_one = (Button) findViewById(R.id.btn_static_one);
        btn_send_two = (Button) findViewById(R.id.btn_static_two);
        btn_send_three = (Button) findViewById(R.id.btn_static_three);
        btn_send_one.setOnClickListener(mOnClickListener);
        btn_send_two.setOnClickListener(mOnClickListener);
        btn_send_three.setOnClickListener(mOnClickListener);
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_static_one:
                    Log.d(TAG,"发送广播1");
                    Toast.makeText(getApplicationContext(), "S广播1 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action1,key1);
                    break;
                case R.id.btn_static_two:
                    Log.d(TAG,"发送广播2");
                    Toast.makeText(getApplicationContext(), "S广播2 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action1,key2);
                    break;
                case R.id.btn_static_three:
                    Log.d(TAG,"发送广播3");
                    Toast.makeText(getApplicationContext(), "S广播3 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action2,key3);
                    break;
            }
        }
    };

    private void sendStaticOrdinary(String action,String key) {
        Intent intent = new Intent();
        if(action.equals(action1)) {
            intent.setAction(CommonClass.ACTION_STATIC_ONE);
        } else if(action.equals(action2)){
            intent.setAction(CommonClass.ACTION_STATIC_TWO);
        }
        if(key.equals(key1)) {
            intent.putExtra(CommonClass.KEY_STATIC_ONE, "fancy1 static one");
        } else if(key.equals(key2)){
            intent.putExtra(CommonClass.KEY_STATIC_TWO, "fancy1 static two");
        } else {
            intent.putExtra(CommonClass.KEY_STATIC_THREE, "fancy2 static two");
        }
        intent.setComponent(new ComponentName(StaticActivity.this,StaticReceiver.class));
        sendBroadcast(intent);
    }

}

activity_static.xml–静态注册布局文件

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/title_bar_static"
            android:layout_marginTop="5dp"
            android:textSize="20sp"
            android:gravity="center"
            android:text="静态注册"/>

        <Button
            android:id="@+id/btn_static_one"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="广播1 密码1"/>

        <Button
            android:id="@+id/btn_static_two"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="广播1 密码2"/>

        <Button
            android:id="@+id/btn_static_three"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="广播2 密码3"/>

    </LinearLayout>
</ScrollView>

StaticReceiver–静态注册接收器

package com.xtc.broadcastalldemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class StaticReceiver extends BroadcastReceiver {

    private static final String TAG = "fancy";
    private String content1,content2,content3;

    public StaticReceiver() {

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG, "action is ->"+action);
        if(action.equals(CommonClass.ACTION_STATIC_ONE)) {
            content1 = intent.getStringExtra(CommonClass.KEY_STATIC_ONE);
            Log.d(TAG, "content1 is ->" + content1);
            content2 = intent.getStringExtra(CommonClass.KEY_STATIC_TWO);
            Log.d(TAG, "content2 is ->" + content2);
        } else if(action.equals(CommonClass.ACTION_STATIC_TWO)) {
            content3 = intent.getStringExtra(CommonClass.KEY_STATIC_THREE);
        }
        if(action.equals(CommonClass.ACTION_STATIC_ONE)) {
            if(content1!=null) {
                Log.d(TAG,"收到静态广播1");
                Toast.makeText(context.getApplicationContext(), content1, Toast.LENGTH_SHORT).show();
            } else {
                Log.d(TAG,"收到静态广播2");
                Toast.makeText(context.getApplicationContext(), content2, Toast.LENGTH_SHORT).show();
            }
        } else if(action.equals(CommonClass.ACTION_STATIC_TWO)){
            Log.d(TAG,"收到静态广播3");
            Toast.makeText(context.getApplicationContext(), content3, Toast.LENGTH_SHORT).show();
        } 
    }
}

CommonClass–公共类

package com.xtc.broadcastalldemo;

public class CommonClass {
    //普通广播
    //定义静态广播标签
    public static final String ACTION_STATIC_ONE = "com.static.fancy_one";
    public static final String ACTION_STATIC_TWO = "com.static.fancy_two";
    public static final String KEY_STATIC_ONE = "static_one";
    public static final String KEY_STATIC_TWO = "static_two";
    public static final String KEY_STATIC_THREE = "static_three";
    //定义动态广播标签
    public static final String ACTION_DYNAMIC_ONE = "com.dynamic.fancy_one";
    public static final String ACTION_DYNAMIC_TWO = "com.dynamic.fancy_two";
    public static final String KEY_DYNAMIC_ONE = "dynamic_one";
    public static final String KEY_DYNAMIC_TWO = "dynamic_two";
    public static final String KEY_DYNAMIC_THREE = "dynamic_three";
    //定义有序广播
    //定义动态广播
    public static final String ACTION_ORDERLY_ONE = "com.orderly.fancy_one";
    public static final String ACTION_ORDERLY_TWO = "com.orderly.fancy_two";
    public static final String ACTION_ORDERLY_THREE = "com.orderly.fancy_three";
}

还需要记得静态注册需要在manifest里面声明

        <receiver
            android:name=".StaticReceiver"
            android:exported="true"
            android:enabled="true">
            <intent-filter>
                <action android:name="com.static.fancy_one"/>
            </intent-filter>
        </receiver>

动态注册广播

动态注册广播的基本概念及注意事项:
自定义一个Receiver类,复写onReceiver方法 (根据action区分不同的广播类型)
新建intentFilter:通过addAction添加感兴趣的广播类型
在Activity中注册广播:registerReceiver(receiver,intentFilter)
!!!不要忘记:一定要在onDestroy的时候unregister,否则会出现内存泄漏
缺点:只有app运行的时候,才能注册广播,如果app未运行,就收不到这个广播

下面是动态注册所需的文件:(以黄色框标注)
在这里插入图片描述
Mainactivity 是主界面,可以选择动态注册还是静态注册。
DynamicActivity 是动态注册
Commonclass 是公共类,静态注册和动态注册都需要用到

MainActivity和CommonClass在上面静态注册已经写过了,这里就不在写了

DynamicActivity–动态注册

package com.xtc.broadcastalldemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
//动态注册广播实例
public class DynamicActivity extends AppCompatActivity {

    private Button btn_send_one,btn_send_two,btn_send_three;
    private static final String TAG = "fancy";
    private String content1,content2,content3;
    private String action1 = "one";
    private String action2 = "two";
    private String key1 = "first";
    private String key2= "second";
    private String key3= "third";

    //第四步
    DynamicReceiver dynamicReceiver = new DynamicReceiver();

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

        btn_send_one = (Button) findViewById(R.id.btn_dynamic_one);
        btn_send_two = (Button) findViewById(R.id.btn_dynamic_two);
        btn_send_three = (Button) findViewById(R.id.btn_dynamic_three);
        btn_send_one.setOnClickListener(mOnClickListener);
        btn_send_two.setOnClickListener(mOnClickListener);
        btn_send_three.setOnClickListener(mOnClickListener);
        registerBatteryReceiver();
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_dynamic_one:
                    Log.d(TAG,"发送广播1");
                    Toast.makeText(getApplicationContext(), "D广播1 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action1,key1);
                    break;
                case R.id.btn_dynamic_two:
                    Log.d(TAG,"发送广播2");
                    Toast.makeText(getApplicationContext(), "D广播2 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action1,key2);
                    break;
                case R.id.btn_dynamic_three:
                    Log.d(TAG,"发送广播3");
                    Toast.makeText(getApplicationContext(), "D广播3 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action2,key3);
                    break;
            }
        }
    };

    /*
     *  动态注册一个广播
     */

    /*
     *  第一步:创建广播接收者,继承自BroadcastReceiver
     */
    private class DynamicReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent==null) return;
            String action = intent.getAction();
            if(action==null) return;
            Log.d(TAG, "action is ->"+action);
            if(action.equals(CommonClass.ACTION_DYNAMIC_ONE)) {
                content1 = intent.getStringExtra(CommonClass.KEY_DYNAMIC_ONE);
                Log.d(TAG, "content1 is ->" + content1);
                content2 = intent.getStringExtra(CommonClass.KEY_DYNAMIC_TWO);
                Log.d(TAG, "content2 is ->" + content2);
            } else {
                content3 = intent.getStringExtra(CommonClass.KEY_DYNAMIC_THREE);
            }
            if(action.equals(CommonClass.ACTION_DYNAMIC_ONE)) {
                if(content1!=null) {
                    Log.d(TAG,"收到动态广播1");
                    Toast.makeText(context.getApplicationContext(), content1, Toast.LENGTH_SHORT).show();
                } else {
                    Log.d(TAG,"收到动态广播2");
                    Toast.makeText(context.getApplicationContext(), content2, Toast.LENGTH_SHORT).show();
                }
            } else {
                Log.d(TAG,"收到动态广播3");
                Toast.makeText(context.getApplicationContext(), content3, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void registerBatteryReceiver() {
        //第二步-->创建意图过滤器
        IntentFilter intentFilter = new IntentFilter();
        //第三步-->设置频道
        intentFilter.addAction(CommonClass.ACTION_DYNAMIC_ONE);
        intentFilter.addAction(CommonClass.ACTION_DYNAMIC_TWO);
        //第五步-->注册广播
        this.registerReceiver(dynamicReceiver,intentFilter);
    }

    /*
     *  发送一个自定义的广播
     */
    private void sendStaticOrdinary(String action,String key) {
        Intent intent = new Intent();
        if(action.equals(action1)) {
            intent.setAction(CommonClass.ACTION_DYNAMIC_ONE);
        } else if(action.equals(action2)){
            intent.setAction(CommonClass.ACTION_DYNAMIC_TWO);
        }
        if(key.equals(key1)) {
            intent.putExtra(CommonClass.KEY_DYNAMIC_ONE, "fancy1 dynamic one");
        } else if(key.equals(key2)){
            intent.putExtra(CommonClass.KEY_DYNAMIC_TWO, "fancy1 dynamic two");
        } else {
            intent.putExtra(CommonClass.KEY_DYNAMIC_THREE, "fancy2 dynamic two");
        }
        sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册广播,否则会导致内存泄漏 (00M)
        unregisterReceiver(dynamicReceiver);
    }
}

activity_dynamic.xml–动态注册布局文件

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/title_bar_dynamic"
            android:layout_marginTop="5dp"
            android:textSize="20sp"
            android:gravity="center"
            android:text="动态注册"/>

        <Button
            android:id="@+id/btn_dynamic_one"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="发送1号广播"/>

        <Button
            android:id="@+id/btn_dynamic_two"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="发送2号广播"/>

        <Button
            android:id="@+id/btn_dynamic_three"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="发送3号广播"/>

    </LinearLayout>
</ScrollView>

二、有序广播

在这里插入图片描述
Mainactivity 是主界面,可以选择动态注册还是静态注册。
OrderlyActivity 是有序广播动态注册
Commonclass 是公共类,静态注册和动态注册都需要用到

orderlyActivity–有序广播

package com.xtc.broadcastalldemo;

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.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class OrderlyActivity extends AppCompatActivity {

    private Button btn_one,btn_two,btn_three;
    OederlyReceiverOne orderlyone = new OederlyReceiverOne();
    OederlyReceiverTwo orderlytwo = new OederlyReceiverTwo();
    OederlyReceiverThree orderlythree = new OederlyReceiverThree();
    FinalReceiver finalReceiver = new FinalReceiver();
    private static final String TAG = "fancy";
    private String action1 = "one";
    private String action2 = "two";
    private String action3 = "three";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderly);
        btn_one = (Button) findViewById(R.id.btn_orderly_one);
        btn_two = (Button) findViewById(R.id.btn_orderly_two);
        btn_three = (Button) findViewById(R.id.btn_orderly_three);
        btn_one.setOnClickListener(mOnClickListener);
        btn_two.setOnClickListener(mOnClickListener);
        btn_three.setOnClickListener(mOnClickListener);
        registerBatteryReceiver();
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_orderly_one:
                    Log.d(TAG,"发送有序广播1");
                    Toast.makeText(getApplicationContext(), "O广播1 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action1);
                    break;
                case R.id.btn_orderly_two:
                    Log.d(TAG,"发送有序广播2");
                    Toast.makeText(getApplicationContext(), "O广播2 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action2);
                    break;
                case R.id.btn_orderly_three:
                    Log.d(TAG,"发送有序广播3");
                    Toast.makeText(getApplicationContext(), "O广播3 已发送", Toast.LENGTH_SHORT).show();
                    sendStaticOrdinary(action3);
                    break;
            }
        }
    };

    private void registerBatteryReceiver() {
        //设置第一个有序广播
        IntentFilter intentFilterone = new IntentFilter();
        intentFilterone.setPriority(1000);
        intentFilterone.addAction(CommonClass.ACTION_ORDERLY_ONE);
        intentFilterone.addAction(CommonClass.ACTION_ORDERLY_TWO);
        intentFilterone.addAction(CommonClass.ACTION_ORDERLY_THREE);
        this.registerReceiver(orderlyone,intentFilterone);
        //设置第二个有序广播
        IntentFilter intentFiltertwo = new IntentFilter();
        intentFiltertwo.setPriority(800);
        intentFiltertwo.addAction(CommonClass.ACTION_ORDERLY_ONE);
        intentFiltertwo.addAction(CommonClass.ACTION_ORDERLY_TWO);
        intentFiltertwo.addAction(CommonClass.ACTION_ORDERLY_THREE);
        this.registerReceiver(orderlytwo,intentFiltertwo);
        //设置第三个有序广播
        IntentFilter intentFilterthree = new IntentFilter();
        intentFilterthree.setPriority(600);
        intentFilterthree.addAction(CommonClass.ACTION_ORDERLY_ONE);
        intentFilterthree.addAction(CommonClass.ACTION_ORDERLY_TWO);
        intentFilterthree.addAction(CommonClass.ACTION_ORDERLY_THREE);
        this.registerReceiver(orderlythree,intentFilterthree);

        IntentFilter intentFilterfinal = new IntentFilter();
        intentFilterthree.setPriority(400);
        intentFilterfinal.addAction(CommonClass.ACTION_ORDERLY_ONE);
        intentFilterfinal.addAction(CommonClass.ACTION_ORDERLY_TWO);
        intentFilterfinal.addAction(CommonClass.ACTION_ORDERLY_THREE);
        this.registerReceiver(finalReceiver,intentFilterfinal);
    }

    /*
     *  发送一个自定义的广播
     */
    private void sendStaticOrdinary(String action) {
        Intent intent = new Intent();
        //收到广播时需要的权限
        String receiverPermission=null;
        //作为最终的广播接收者
        BroadcastReceiver resultReceiver =null;
        //处理最终的广播接收者用到Handler 如果传null会在主线程处理
        Handler scheduler=null;
        //初始化数据
        String initialData=null;
        if(action.equals(action1)) {
            initialData="新年快乐~1";
            intent.setAction(CommonClass.ACTION_ORDERLY_ONE);
        } else if(action.equals(action2)){
            initialData="当前气温 30°";
            intent.setAction(CommonClass.ACTION_ORDERLY_TWO);
        } else if(action.equals(action3)) {
            initialData="海拔3000米";
            intent.setAction(CommonClass.ACTION_ORDERLY_THREE);
        }
        sendOrderedBroadcast(intent,receiverPermission,resultReceiver,scheduler,RESULT_OK,initialData,null);
    }

    private class OederlyReceiverOne extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent==null) return;
            String action = intent.getAction();
            if(action==null) return;
            String resultData = getResultData(); //获取数据
            if(action.equals(CommonClass.ACTION_ORDERLY_ONE)) {
                Log.d(TAG,"收到1号广播第一阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("新年快乐~2");
                //abortBroadcast(); //终止广播
            } else if (action.equals(CommonClass.ACTION_ORDERLY_TWO)) {
                Log.d(TAG,"收到2号广播第一阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("当前气温 25°");
            } else if (action.equals(CommonClass.ACTION_ORDERLY_THREE)) {
                Log.d(TAG,"收到3号广播第一阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("海拔3500米");
            }
        }
    }

    private class OederlyReceiverTwo extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent==null) return;
            String action = intent.getAction();
            if(action==null) return;
            String resultData = getResultData(); //获取数据
            if(action.equals(CommonClass.ACTION_ORDERLY_ONE)) {
                Log.d(TAG,"收到1号广播第二阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("新年快乐~3");
            } else if (action.equals(CommonClass.ACTION_ORDERLY_TWO)) {
                Log.d(TAG,"收到2号广播第二阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("当前气温 20°");
            } else if (action.equals(CommonClass.ACTION_ORDERLY_THREE)) {
                Log.d(TAG,"收到3号广播第二阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("海拔播报终止");
            }
        }
    }

    private class OederlyReceiverThree extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent==null) return;
            String action = intent.getAction();
            if(action==null) return;
            String resultData = getResultData(); //获取数据
            if(action.equals(CommonClass.ACTION_ORDERLY_ONE)) {
                Log.d(TAG,"收到1号广播第三阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("新年快乐~over");
            } else if (action.equals(CommonClass.ACTION_ORDERLY_TWO)) {
                Log.d(TAG,"收到2号广播第三阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("当前气温~over");
            } else if (action.equals(CommonClass.ACTION_ORDERLY_THREE)) {
                Log.d(TAG,"收到3号广播第三阶段");
                Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
                setResultData("海拔4000米~over");
                abortBroadcast(); //终止广播
            }
        }
    }

    private class FinalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent==null) return;
            String action = intent.getAction();
            if(action==null) return;
            String resultData = getResultData(); //获取数据
            Log.d(TAG,"收到广播最终阶段");
            Toast.makeText(context.getApplicationContext(), resultData, Toast.LENGTH_SHORT).show();
        }
    }
}

activity_orderly–布局文件

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/title_bar_static"
            android:layout_marginTop="5dp"
            android:textSize="18sp"
            android:gravity="center"
            android:text="动态有序广播"/>

        <Button
            android:id="@+id/btn_orderly_one"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="广播1 逐级发送"/>

        <Button
            android:id="@+id/btn_orderly_two"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="广播2 逐级修改"/>

        <Button
            android:id="@+id/btn_orderly_three"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="15sp"
            android:textColor="@color/black"
            android:text="广播3 中间截断"/>

    </LinearLayout>
</ScrollView>

三、Android 源码里使用广播

    private void registerReceive() {
        IntentFilter intentFilter =new IntentFilter();
        intentFilter.addAction(ACTION_CLASS_DISABLE);
        getContext().registerReceiver(SpaceCleanReceiver,intentFilter);
    }

    private final BroadcastReceiver SpaceCleanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent==null) return;
            String action = intent.getAction();
            if(action==null) return;
            if( action.equals(ACTION_CLASS_DISABLE) ) {
                Slog.d(TAG,"Special mode pause prompt,the action is "+action);
                scheduledSpaceClean(null,false);
            }
        }
    };

至此广播的静态注册和动态注册及普通和有序广播就讲解完了,想要源码或者有疑问的小伙伴,可以留言~

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-04-26 11:52:02  更:2022-04-26 11:54:51 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 23:53:40-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码