BroadcastReceiver 身为安卓的四大组件之一,其使用率非常普遍,所以我们要熟练掌握其使用方法。
1,广播的注册方式有两种:静态注册和动态注册
1),静态注册:需要在Androidmanifest 中进行声明,主要用于全局APP中监听,只有完全退出APP才能让其停止工作。
2),动态注册:在代码中注册,不需要在Androidmanifest进行声明,其生命周期随着活动的开始而开始,结束而结束,主要用于当前活动的监听。
2,广播的种类:有序广播和无序广播
1),有序广播:广播按照一定的顺序被接收,优先级高的比优先级低的先接收到,并且优先级高的可以阻断和添加数据给优先级低的广播。
2),无序广播:无论是否有广播接收器,都会发送广播,接收前后顺序不受优先级影响,也不能被阻断,接收器也不能对其修改。
效果图如下:
下面直接上代码:
主界面代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.btzh.mybroatcasttest.MainActivity">
<Button
android:text="无序广播"
android:id="@+id/send_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="当前Activity广播"
android:id="@+id/send_btn_1"
android:layout_below="@id/send_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="有序广播"
android:id="@+id/send_btn_2"
android:layout_below="@id/send_btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:text=""
android:id="@+id/text_view"
android:layout_below="@id/send_btn_2"
android:layout_width="match_parent"
android:layout_height