Android编程学习笔记 之 BroadcastReceiver组件

BroadcastReceiver,广播接收器,是Android四大组件之一。需要在AndroidManifest.xml注册或者用代码动态注册。

它的生命周期很短,只有十秒左右,所以不能执行耗时操作,否则会造成ANR错误。

如果需要进行操作,可以用intent启动一个Service完成。

并且,不能使用子线程,当BroadcastReceiver生命周期结束时,它的子线程也会关闭。


使用BroadcastReceiver的步骤:

创建BroadcastReceiver的子类并重写onReceive()方法

注册BroadcastReceiver子类(动态注册 或 静态注册)

发送广播,调用onReceive()方法接收


广播有三种形式,普通广播(Broadcast)有序广播(OrderedBroadcast)异步广播(StickyBroadcast)

他们有以下共同的特点

①所有发送的广播都能接收到,相同优先级的广播的接收顺序随机无序
②优先级高的先接收到广播,优先级低的后接收到广播
④相同优先级的动态注册优先于静态注册


除了相同的地方外,它们还有一些不同点

普通广播:接收器不能截断广播,也不能处理广播。

有序广播:接收器可以截断广播,也可以处理广播。

异步广播:接收器不能截断广播,也不能处理广播。可以先发送,再注册BroadcastReceiver。

异步广播要在AndroidManifest.xml中声明权限

<uses-permission android:name="android.permission.BROADCAST_STICKY"/>

创建BroadcastReceiver的子类并重写onReceive()方法

由于BroadcastReceiver是抽象类,所以我们要创建子类并重写其中的方法。

用getXxxExtra获取Intent中的数据。或者开启一个Service服务完成耗时操作。

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {//context表示上下文,intent表示BroadcastReceiver接收到意图
        String msg = intent.getStringExtra("key");//获取intent中的数据,并显示出来
        Toast.makeText(context, "BC_first:"+msg, Toast.LENGTH_SHORT).show();
    }
}


注册BroadcastReceiver子类(动态注册 或 静态注册)

注册BroadcastReceiver有两种方法,静态注册和动态注册。

静态注册,就是在AndroidManifest.xml中进行注册,类似于Activity的注册。

<receiver android:name = "包名.BC1"><!--自定义BroadcastReceiver的类名-->
	<intent-filter android:priority="100"><!--优先级为100-->
		<action android:name = "BC_one"><!--设置action的名字用以访问该receiver-->
	</intent-filter>
<receiver>

除了静态注册,还可以在代码中动态注册,但是要注意代码的生命周期,并且在使用完毕后,要注销注册

一般在onStart中注册,onStop中注销unregisterReceiver

IntentFilter intentfilter = new IntentFilter("BC_normal");//创建intent-fliter并设置action的值
BC2 bc2 = new BC2();//创建自定义BroadcastReceiver的对象
registerReceiver(bc2, intentfilter);//进行动态注册

unregisterReceiver(bc2);//在使用完毕后进行注销注册
相同优先级的动态注册优先于静态注册

已经注册的BroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent匹配,

如果匹配就调用BroadcastReceiver中的onReceive()方法。


发送广播,调用onReceive()方法接收

发送广播有三种方式,在上面有提到这三种区别。
Intent intent = new Intent("BC_normal");
intent.putExtra("key", "这是一条广播");//存储数据

void sendBroadcast(Intent intent);//发送普通广播
void sendOrderBroadcast(Intent intent, String receiverPermission);//发送有序广播,第二个参数是设置权限,即接收器必须具有相应的权限才能正常接收到广播。
void sendStickyBroadcast(Intent intent);//发送异步广播

发送完毕后,在第一步中的onReceive()方法就会被调用。


以下放上demo源码

//主Activity
public class MainActivity extends Activity {
    Intent intent = new Intent();
    MyBroadcastReceiver3 myBC3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    }
    public void click(View view){

        switch (view.getId()){
            case R.id.send1:
                intent.setAction("BC");
                intent.putExtra("key", "这是一条普通广播");
                sendBroadcast(intent);//发送普通广播
                break;
            case R.id.send2:
                intent.setAction("BC");
                intent.putExtra("key", "这是一条有序广播");
                sendOrderedBroadcast(intent, null);//发送有序广播,接收权限为null
                break;
            case R.id.send3:
                intent.setAction("BC_sticky");
                intent.putExtra("key", "这是一条异步广播");
                sendStickyBroadcast(intent);//发送异步广播

                IntentFilter intentFilter = new IntentFilter("BC_sticky");//进行动态注册
                myBC3 = new MyBroadcastReceiver3();
                registerReceiver(myBC3, intentFilter);
                break;
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(myBC3);//进行注销动态注册
    }
}
<!--AndroidManifest.xml-->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ahao.demo">
    <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"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MyBroadcastReceiver1"><!--实现的类名-->
            <intent-filter android:priority="200"><!--优先级为200-->
                <action android:name="BC"/><!--访问的Action名-->
            </intent-filter>
        </receiver>
        <receiver android:name=".MyBroadcastReceiver2"><!--实现的类名-->
            <intent-filter android:priority="100"><!---优先级为100->
                <action android:name="BC"/><!--访问的Action名-->
            </intent-filter>
        </receiver>
    </application>
</manifest>
<!--主Activity的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/send1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="发送一条普通广播"/>
    <Button
        android:id="@+id/send2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="发送一条有序广播"/>
    <Button
        android:id="@+id/send3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="发送一条异步广播"/>
</LinearLayout>
//第一个BroadcastReceiver广播
public class MyBroadcastReceiver1 extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String msg = intent.getStringExtra("key");
        Toast.makeText(context, "BC_first:"+msg, Toast.LENGTH_SHORT).show();
//以下为有序广播内容
//        abortBroadcast();//如果截断广播,则下一级receiver不能接收到广播,且不能处理广播
        Bundle bundle = new Bundle();
        bundle.putString("order_msg", "BC1传给下一级BC2的数据");//数据包
        setResultExtras(bundle);//处理广播

    }
}
//第二个BroadcastReceiver广播
public class MyBroadcastReceiver2 extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String msg = intent.getStringExtra("key");
        Toast.makeText(context, "BC_second:" + msg, Toast.LENGTH_SHORT).show();
//以下为有序广播内容
        String order_msg = getResultExtras(true).getString("order_msg");//接收上一级receiver处理过的广播
        if(order_msg!=null) {
            Toast.makeText(context, "order_msg:" + order_msg, Toast.LENGTH_SHORT).show();
        }
    }
}
//第三个BroadcastReceiver广播,异步广播
public class MyBroadcastReceiver3 extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String msg = intent.getStringExtra("key");
        Toast.makeText(context, "BC_sticky:" + msg, Toast.LENGTH_SHORT).show();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值