[安卓开发] Broadcast 三种广播的使用总结

1、什么是安卓的Broadcast?

安卓的四大组件之一,是一种广泛应用在应用程序之间传输信息的机制。

2、什么是安卓的BroadcastReceiver?

是对发送出来的广播进行过滤接收并响应的一类组件,它就是用来接收来自系统和应用中的广播。例如系统的广播有开机广播: 系统在开机时候会发送开机广播,程序接收到之后,能进行开机自启动。 网络状态改变广播: 3g变wifi、网络断开等。电量改变广播等等。。。

3、Anroid为什么要这样设计?

大大减少开发工作量和开发周期
作为开发者,只需要掌握BroadcastReceiver

4、怎么理解Broadcast和BroadcastReceiver ?

Broadcast就像现实中的广播电台,他发广播信号来,然后我们用收音机来接收,然后处理,并且播放出声音, BroadcastReceiver就相当于那台收音机。

5、使用方法

  • 发送:

把信息装入一个Intent对象(如:Action、Category),通过调相应的方法将Intent对象以广播的方式发送出去:
sendBroadcast();
sendOrederBroadcast();
sendStickyBroadcast();

  • 接收:

当Intent发送之后,所有已经注册receivedBroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent相匹配,若匹配则就会调用BroadcastReceiver的onReceiver()方法。所以当我们定义一个BroadcastReceiver的时候,都需要实现onReceiver()方法。

  • 注意:

BroadcastReceiver需要注册
静态注册
代码动态注册

6、注意!!!!

BroadReceiver生命周期只有十秒左右,不能直接执行耗时操作,不然会出现ANR(应用程序无响应),也不能用子线程来做,因为每次广播来的时候都会创建一个Reveiver对象,并且调用onReceiver,执行完之后 ,对象会立刻被销毁,子线程也没了
要做耗时操作的话,应该通过发送Intent给Service,由Service来完成。
动态注册广播接受者的话要在Destory回调事件进行unregister

7、广播的分类

  • 普通广播 (Normal broadcast)
  • 所有监听该广播接受者都可以监听到该广播
  • 同级别接收先后顺序是随机的(无序)
  • 级别低的后收到广播
  • 接收器不能截断广播的继续传播,也不能处理广播
  • 同级别动态注册高于静态注册
  • 有序广播 (Oredered broadcast)
  • 按照接收者的优先顺序来接收广播,优先级别在intent-filter中的priority中声明,-1000到1000之间,值越大优先级越高,可以终止广播的继续传播,接受者可以修改intent的内容。
  • 同级别接收顺序是随机的
  • 级别低的后收到
  • 能截断广播的继续传播,高级别的广播接收器接收广播后能决定时候截断。
  • 能处理广播
  • 同级别动态注册高于静态注册
  • 异步广播 (粘滞性滞留广播) ps:已被弃用
  • 不能处理结果给下一个接收者,无法终止广播。
  • 一直存在
  • 可以先发送广播,再注册接收器
  • 需要在清单文件添加android.permission.BROADCAST_STICKY权限

8、Demo

布局actibity_main三个按钮:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/bt_one"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="普通广播" />

    <Button
        android:id="@+id/bt_two"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="有序Ordered广播" />

    <Button
        android:id="@+id/bt_three"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="异步广播Sticky粘滞性滞留广播" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btOne;
    private Button btTwo;
    private Button btThree;


    MyReiceiverThree myReiceiver = new MyReiceiverThree();

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

        btOne = (Button) findViewById(R.id.bt_one);
        btTwo = (Button) findViewById(R.id.bt_two);
        btThree = (Button) findViewById(R.id.bt_three);

        btOne.setOnClickListener(this);
        btTwo.setOnClickListener(this);
        btThree.setOnClickListener(this);


        //动态注册,在当前activity的生命周期內运行
        /*IntentFilter filter= new IntentFilter(Config.BC_ONE_ACTION);
        MyReiceiver myReiceiver = new MyReiceiver();
        registerReceiver(myReiceiver,filter);*/

    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()){
            case R.id.bt_one:      //发送普通广播
                intent.setAction(Config.BC_ONE_ACTION);
                intent.putExtra("msg","这是普通广播");
                sendBroadcast(intent);
                break;
            case R.id.bt_two:     //有序广播
                intent.setAction(Config.BC_TWO_ACTION);
                intent.putExtra("msg","这是有序广播");
                sendOrderedBroadcast(intent,null);  //其中第二个参数是设置权限,即接收器必须具有相应的权限才能正常接收到广播。
                break;
            case R.id.bt_three:   //异步广播
                intent.setAction(Config.BC_THREE_ACTION);
                intent.putExtra("msg","这是异步广播");
                sendStickyBroadcast(intent);

                //可以先发送 后注册
                IntentFilter filter = new IntentFilter(Config.BC_THREE_ACTION);

                registerReceiver(myReiceiver, filter);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReiceiver);
    }
}

MyReceiver.java

public class MyReiceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        //获取处理的的广播,普通广播不能获取处理
        //true代表如果前面的接收器没有存放数据,则自动创建一个空的Bundle对象,false则表示如果前面的接收器如果没有存放任何数据则返回null。
        Bundle  bundle= getResultExtras(true);
        System.out.println("接收器1接收到处理的值:"+bundle.getString("msg"));

        System.out.println("接收器1:"+intent.getStringExtra("msg"));
    }
}

MyReceiverTwo.java

public class MyReiceiverTwo extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Toast.makeText(context,intent.getStringExtra("msg"),Toast.LENGTH_SHORT).show();
        System.out.println("接收器2:"+intent.getStringExtra("msg"));

        abortBroadcast();    //截断广播,不让别的接收器继续接收,有序广播才能成功拦截

        //处理广播
        Bundle bundle = new Bundle();
        bundle.putString("msg","处理过后的广播");
        setResultExtras(bundle); //
    }
}

MyReceiverThree.java

public class MyReiceiverThree extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Toast.makeText(context,intent.getStringExtra("msg"),Toast.LENGTH_SHORT).show();
        System.out.println("接收器3:"+intent.getStringExtra("msg"));

    }
}

Config.java

public class Config {
    public static final String BC_ONE_ACTION = "com.example.testbroadcasetwo.bcone";
    public static final String BC_TWO_ACTION = "com.example.testbroadcasetwo.bctwo";
    public static final String BC_THREE_ACTION = "com.example.testbroadcasetwo.bcthree";
}

Androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testbroadcasetwo">

    //异步广播需要 一个权限
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        //静态注册,全局有效
        //第一个接收器
        <receiver android:name=".MyReiceiver">
            <intent-filter android:priority="10">//添加级别
                <action android:name="com.example.testbroadcasetwo.bcone" />
            </intent-filter>
        </receiver>

        //第二个接收器
        <receiver android:name=".MyReiceiverTwo">
            <intent-filter android:priority="11">//添加级别
                <action android:name="com.example.testbroadcasetwo.bcone" />
            </intent-filter>
        </receiver>


    </application>

</manifest>

Demo下载地址: http://download.csdn.net/detail/niubitianping/9577865

9、onReceiver回调更新ui
注意: 必须使用动态注册才能实现回调更新ui
目录结构:
这里写图片描述

Confiug.java 定义一个常量作为action

public class Config {
    public static String BC_ONE = "com.example.testbroadcast.bcone";
}

TYPE.java 枚举类,集合,没用了,用来判断是什么广播的

public enum TYPE {
    NORMAL
}

HandleBroadcas.java p层的处理数据类

public class HandleBroadcast {

    private IShowView iShowView;
    private Context context;

    public HandleBroadcast(final IShowView iShowView, Context context) {
        this.iShowView = iShowView;
        this.context = context;

        //必须动态注册才能实现回调
        MyBroadcastReceiver broadcast = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Config.BC_ONE);
        context.registerReceiver(broadcast, intentFilter);


        broadcast.setiShowView(new IShowView() {
            @Override
            public void updateText(String msg) {
                iShowView.updateText(msg);
            }
        });
    }


    public void sendMyBroadcast(TYPE type) {

        Intent intent = new Intent();
        switch (type) {
            case NORMAL:   //普通广播
                intent.putExtra("msg", "普通广播发送成功");
                intent.setAction(Config.BC_ONE);
                context.sendBroadcast(intent);
                break;
        }
    }

}

MyBroadcast.java 广播接收器

public class MyBroadcastReceiver extends BroadcastReceiver {

    private IShowView iShowView;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        String msg = intent.getStringExtra("msg");
        iShowView = (MainActivity) context;
        if (action.equals(Config.BC_ONE)) { //接收到普通广播
            iShowView.updateText(msg);    //回调给HandleBroadcast
        }
    }

    public void setiShowView(IShowView iShowView) {
        this.iShowView = iShowView;
    }
}

IShowView.java 回调到activity更新ui的接口

public interface IShowView {

    void updateText(String msg);

}

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener,IShowView{

    private Button btOne;

    private TextView mTvResult;

    //p层,处理数据
    private HandleBroadcast handleBroadcast;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handleBroadcast = new HandleBroadcast(this,this);

        btOne = (Button) findViewById(R.id.bt_one);
        mTvResult = (TextView) findViewById(R.id.tv_result);
        btOne.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_one:
                handleBroadcast.sendMyBroadcast(TYPE.NORMAL);
                break;
        }
    }


    /**
     * 广播接收处理完毕之后回调更新ui
     * @param msg 要显示的文字
     */
    @Override
    public void updateText(String msg) {
        mTvResult.setText(msg);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/bt_one"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="发送广播"
        />
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="结果"
        android:gravity="center"
        />
</LinearLayout>

mvp模式的demo下载:http://download.csdn.net/detail/niubitianping/9577879

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KeepStudya

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值