Android 广播实例汇总-普通广播 有序广播及静态注册、动态注册详解附源码讲解_ys.journey的博客-程序员秘密_android 广播实例

技术标签: java  android  android studio  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);
            }
        }
    };

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/fancynthia/article/details/124359900

智能推荐

git push send-pack: unexpected disconnect while reading sideband packet_ITKEY_的博客-程序员秘密_unexpected disconnect while reading sideband packe

错误信息git push枚举对象中: 200, 完成.对象计数中: 100% (200/200), 完成.使用 8 个线程进行压缩压缩对象中: 100% (183/183), 完成.写入对象中: 100% (199/199), 20.87 MiB | 25.02 MiB/s, 完成.总共 199(差异 17),复用 0(差异 0),包复用 0error: RPC 失败。HTTP 413 curl 22 The requested URL returned error: 413send-pa

linux 命令行中使用无参数 双横线(--)的意义_chuluo9869的博客-程序员秘密

一.缘起:使用php composer时想到 composer.phar包,想找到并调试某个信息; 二. 阅读相关文章: linux下安装composer 发现如下命令: //你可以通过 --install-dir 选项指定 Composer 的安装目录(它可以是一个绝对或相...

Redis 存储List对象_Leolu007的博客-程序员秘密

rn rv;          }            public static List deserialize(byte[] in) {              List list = new ArrayList();              ByteArrayInputStream bis = null;              ObjectInputStr

Windows安装python3.6.x版本_cx_baby的博客-程序员秘密_python环境(3.7.x 或者3.6.x版本)

下载python安装程序1.官网下载python的windows版本python官方网站:https://www.python.org/ 如下图,选择需要的版本下载即可。我这里下载Python3.6.7版本点击Download,在新跳出的页面,选择对应版本,这里我选择如图windows x86 安装程序。安装pthon3.6.7找到下载的安装程序,双击打开。弹出的对话框如下...

Python中enumerate()内置函数的详细介绍_在银河中心的博客-程序员秘密_python enum get_item

enumerate枚举列举1.对可以迭代的数据进行标号,并打印出来2.什么是可以迭代的数据?可迭代对象并不是指某种具体的数据类型,它是指存储了元素的一个容器对象,且容器中的元素可以通过__iter__( )方法或__getitem__( )方法访问。3.什么是__iter__( )方法和__getitem__( )方法?__iter__方法的作用是:让对象可以用for ... in循环遍历 __getitem__( )方法是:让对象可以通过“实例名[index]”的方式访问实例中的元素

J2EE程序员_kingsure的博客-程序员秘密_j2ee程序员

通过死活挣扎,终于掉回了自己的故乡的分公司~~~~~刚好接受一个要辞职的同事的工作,一个J2EE开发者~~~~~通过一番交流,主要利用了STRUTS来处理各种业务流程, 单刀直入,直接看Action, 虽然我对J2EE开发不是非常熟悉,但是有几年的J2SE实战经验,看了第一个ACTION就发现了不少J2EE程序员的通病(可能会有N多兄弟砸鸡蛋给我),对JAVA的基本程序设计模式的利用几乎是

随便推点

C++ 并发指南 std::atomic_flag_碎步の流年的博客-程序员秘密_std::atomic_flag

本文介绍 &lt; atomic &gt; 头文件中最简单的原子类型: atomic_flag。atomic_flag 一种简单的原子布尔类型,只支持两种操作,test-and-set 和 clear。std::atomic_flag 构造函数std::atomic_flag 构造函数如下:atomic_flag() noexcept = default;atomic_flag (const atomic_flag&amp;T) = delete;std::atomic_flag 只有默认构造

重拾设计模式-状态模式_只因啊的博客-程序员秘密

简介:状态模式是当一个对象的内置状态改变时允许改变其行为,主要解决的是当一个对象状态转换逻辑较复杂时,将这些逻辑转移到其他类中进行分离。代码实现及测试如下:public interface State { void handle();}public class ConcreteStateA implements State { @Override public void han...

Android基础笔记(六)-网络编程_别志华的博客-程序员秘密

解决交互的乱码多线程下载-玩具程序多线程下载与续传-玩具程序Android下多线程下载-玩具程序XUtils下载文件解决交互的乱码交互乱码的根本原因就是平台两端的字符编码不一致需要注意的点:Andriod使用HttpUrlConnection的Get和Post方式提交,都不会帮我们进行编码,如果有中文就会出现乱码。需要我们使用URLEncoder.encode()方法对参数进行编码。多

哈密尔顿回路 - 杂录_iCrEjfuhhChXjVz的博客-程序员秘密

哈密尔顿回路1859年,爱尔兰数学家哈密尔顿(Hamilton) 提出了一个周游世界的游戏在正十二面体上依次标记伦敦、巴黎、莫斯科等世界著名大城市, 正十二面体的棱表示连接这些城市的路线.试问能否在图中做一次旅行, 从顶点到顶点, 沿着边行走, 经过每个城市一次之后再回到出发点.转载于 (https://www.jianshu.com/p/57bd58cf8115)哈密尔顿回路是指不重复走过所有点,最后回到起点的路。void dfs(int start, int last, int i, i

13、linux系统启动流程_weixin_33890499的博客-程序员秘密

1、linux系统的组成部分:内核:对进程、内存、网络协议栈、文件系统、驱动程序、安全功能等进行管理根文件系统2、运行中的系统环境分两层:内核空间:又叫内核模式;运行内核级代码,主要实现系统调用用户空间:又叫应用程序;运行用户级别的进程或线程。3、内核存放的位置:/boot:4、rootfs:根文件系统:有/下的必须的一些目录,...

VueJS 基础部分-组件化(2)_zcodery的博客-程序员秘密

第一章 组件化1.1 认识组件化组件化就是将一个页面拆分成一个个小的功能模块,每个功能模块完成属于自己这部分独立的功能,使得整个页面的管理和维护变得非常容易1.2 组件的基本使用过程&lt;div id="app"&gt; &lt;!-- 3. 使用组件 --&gt; &lt;my-cpn&gt;&lt;/my-cpn&gt; &lt;my-cpn&gt;&lt;/my-cpn&gt; &lt;my-cpn&gt;&lt;/my-cpn&gt;&lt;/div&

推荐文章

热门文章

相关标签