一、静态广播注册
MainActivity.java
public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn_send)
Button mBtnSend;
@BindView(R.id.btn_unregister)
Button mBtnUnregister;
@BindView(R.id.btn_register)
Button mBtnRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick({R.id.btn_send})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btn_send:
Intent intent = new Intent();
//注意setAction与AndroidManifest中的action对应
intent.setAction("com.toly1994.aii_broadcastreceiver.StaticBR");
intent.putExtra("msg" , "张风捷特烈");
sendBroadcast(intent);
break;
}
}
}
静态注册广播接受者:StaticBR.java
/**
* 作者:张风捷特烈
* 时间:2018/4/14:16:22
* 邮箱:1981462002@qq.com
* 说明:静态注册广播接受者
*/
public class StaticBR extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("msg");
ToastUtil.show(context, msg + "\n第一个简单广播创建成功!");
}
}
静态注册:app/src/main/AndroidManifest.xml
<receiver android:name=".StaticBR">
<intent-filter>
<action android:name="com.toly1994.aii_broadcastreceiver.MyBroadcastReceiver"/>
</intent-filter>
</receiver>
经测试,Android8.0无法收到静态广播,Android7.0可以法收到静态广播
静态注册一大好处是可以跨程序使用,A程序中的BroadcastReceiver可以在B程序中使用
Android8.0静态广播解决方案:intent.setComponent(new ComponentName(包全名,类全名))
intent.setComponent(new ComponentName("com.toly1994.aii_broadcastreceiver",
"com.toly1994.aii_broadcastreceiver.StaticBR"));
二、动态注册
在未注册之前,点击发送无效果,在注册后点击发送有效果,在注销之后点击无效果。
点击的三个核心代码见下。
注册方法:
IntentFilter filter = new IntentFilter();
filter.addAction("com.toly1994.aii_broadcastreceiver.register");
mReceiver = new StaticBR();
registerReceiver(mReceiver, filter);
发送方法:
Intent intent = new Intent();
//注意setAction与AndroidManifest中的action对应
intent.setAction("com.toly1994.aii_broadcastreceiver.register");
intent.putExtra("msg", "张风捷特烈");
sendBroadcast(intent);
注销方法:
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
附录:布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="发送广播"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="@+id/btn_unregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:text="注销广播"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="@+id/btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="注册广播"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
三、安卓基础之BroadcastReceiver有序广播
先讲个场景小故事:
从前,有个小男孩捡到一颗漂亮的石头,他想去卖,价格1元。
男孩(Boy)大喊:"我有一个漂亮的石头,只卖1元",一个石匠买了这个石头。
石匠(Stonemason)大喊:"我有一个漂亮的石头,只卖1000元。"一个雕刻家买了这个石头。
雕刻家(Graver)大喊:"我有一个漂亮的石头,只卖10w元。"一个宝石家买了这个石头。
宝石家(RubyMan)大喊:"我有一个漂亮的石头,只卖1000w元。"收藏家买了这个石头。
收藏家(Collector)不喊了,静静地收藏起来。男孩用一元买了一个棒棒糖,开心地吃着。故事结束。
按照这个顺序,只要某个人不喊了,任何一个环节都可以被打断,而导致石头的价格出现差异。这就是有序广播的作用。
1.男孩广播接收者:BR1_Boy.java
public class BR1_Boy extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//[1]获取到发送广播携带的数据
String content = getResultData();
//[2]展示到Toast上
Toast.makeText(context, "男孩:" + content, Toast.LENGTH_LONG).show();
// [2.1]终止广播
// abortBroadcast();
//[3]传递数据
setResultData("我有一个漂亮的石头,只卖1000元");
}
}
2.石匠广播接收者:BR2_Stonemason.java
public class BR2_Stonemason extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//[1]获取到发送广播携带的数据
String content = getResultData();
//[2]展示到Toast上
Toast.makeText(context, "石匠:" + content, Toast.LENGTH_LONG).show();
// [2.1]终止广播
// abortBroadcast();
//[3]传递数据
setResultData("我有一个漂亮的石头,只卖10W元");
}
}
3.雕刻家广播接收者:BR3_Graver.java
public class BR3_Graver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//[1]获取到发送广播携带的数据
String content = getResultData();
//[2]展示到Toast上
Toast.makeText(context, "雕刻家:" + content, Toast.LENGTH_LONG).show();
// [2.1]终止广播
// abortBroadcast();
//[3]传递数据
setResultData("我有一个漂亮的石头,只卖1000W元");
}
}
4.宝石家广播接收者:BR4_RubyMan.java
public class BR4_RubyMan extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//[1]获取到发送广播携带的数据
String content = getResultData();
//[2]展示到Toast上
Toast.makeText(context, "宝石家:" + content, Toast.LENGTH_LONG).show();
// [2.1]终止广播
// abortBroadcast();
//[3]传递数据
setResultData("我有一个漂亮的石头,价值1000W元");
}
}
5.收藏家广播接收者:BR5_Collector.java
/**
* 最终的receiver 不需要再清单文件里面配置
*/
public class BR5_Collector extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String content = getResultData();
Toast.makeText(context, "收藏家:" + content, Toast.LENGTH_LONG).show();
}
}
6.记得注册:app/src/main/AndroidManifest.xml
<receiver android:name=".stone.BR1_Boy"></receiver>
<receiver android:name=".stone.BR2_Stonemason"></receiver>
<receiver android:name=".stone.BR3_Graver"></receiver>
<receiver android:name=".stone.BR4_RubyMan"></receiver>
7.StoneStoryActivity.java
public class StoneStoryActivity extends AppCompatActivity {
@BindView(R.id.id_btn_send)
Button mIdBtnSend;
@BindView(R.id.id_btn_reg)
Button mIdBtnReg;
private BR1_Boy mBr1_boy;
private BR2_Stonemason mBr2_stonemason;
private BR3_Graver mBr3_graver;
private BR4_RubyMan mBr4_rubyMan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story);
ButterKnife.bind(this);
}
@OnClick({R.id.id_btn_send, R.id.id_btn_reg})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.id_btn_send:
Intent intent_order = new Intent();
intent_order.setAction("www.toly1994.com");
sendOrderedBroadcast(intent_order, null,
new BR5_Collector(), null, 1,
"我有一个漂亮的石头,只卖1元", null);
break;
case R.id.id_btn_reg://动态注册所有
IntentFilter filter = new IntentFilter();
filter.addAction("www.toly1994.com");
mBr1_boy = new BR1_Boy();
mBr2_stonemason = new BR2_Stonemason();
mBr3_graver = new BR3_Graver();
mBr4_rubyMan = new BR4_RubyMan();
registerReceiver(mBr1_boy, filter);
registerReceiver(mBr2_stonemason, filter);
registerReceiver(mBr3_graver, filter);
registerReceiver(mBr4_rubyMan, filter);
break;
}
}
}
8.如果石匠截断,不喊了,直接卖给收藏家
public class BR2_Stonemason extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//[1]获取到发送广播携带的数据
String content = getResultData();
//[2]展示到Toast上
Toast.makeText(context, "石匠:" + content, Toast.LENGTH_LONG).show();
// [2.1]终止广播
abortBroadcast();
//[3]传递数据
setResultData("我有一个漂亮的石头,价值1000元");
}
}
附录、activity_story.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".StoneStoryActivity">
<Button
android:id="@+id/id_btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="发送广播"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="@+id/id_btn_reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="8dp"
android:text="注册所有广播"
app:layout_constraintBottom_toBottomOf="@+id/id_btn_send"
app:layout_constraintStart_toEndOf="@+id/id_btn_send"
app:layout_constraintTop_toTopOf="@+id/id_btn_send"
app:layout_constraintVertical_bias="1.0"/>
</android.support.constraint.ConstraintLayout>
四、BroadcastReceiver实现锁、开屏、短信监听
1.按电源键,屏幕锁屏,再按电源键屏幕打开。在Activity开启时注册广播用来监听屏幕的关闭,Activity关闭时移除广播。
2.这里只能在该Activity中监听,退出后BroadcastReceiver被注销,后面将会结合Service增强应用范围
3.后面也会结合传感器进行摇晃开屏,暗环境锁屏功能
4.短信监听,可以当收到短信时处理,比如提醒、备份、上传网络、删除、自动回复等
1:InnerActivity.java
public class InnerActivity extends AppCompatActivity {
private ScreenReceiver mScreenReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gary);
ButterKnife.bind(this);
regist();
}
/**
* 动态的去注册屏幕解锁和锁屏的广播
*/
private void regist() {
// [1]动态的去注册屏幕解锁和锁屏的广播
mScreenReceiver = new ScreenReceiver();
// [2]创建intent-filter对象
IntentFilter filter = new IntentFilter();
// [3]添加要注册的action
filter.addAction("android.intent.action.SCREEN_OFF");
filter.addAction("android.intent.action.SCREEN_ON");
// [4]注册广播接收者
registerReceiver(mScreenReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//当activity销毁的时候 取消注册广播接收者
unregisterReceiver(mScreenReceiver);
}
}
2:广播接收者:ScreenReceiver.java
public class ScreenReceiver extends BroadcastReceiver {
private static final String TAG = "ScreenReceiver";
@Override
public void onReceive(Context context, Intent intent) {
//[1]获取到当前广播的事件类型
String action = intent.getAction();
//[2]对当前广播事件类型做一个判断
if ("android.intent.action.SCREEN_OFF".equals(action)) {
Log.i(TAG, "屏幕锁屏了");
} else if ("android.intent.action.SCREEN_ON".equals(action)) {
Log.i(TAG, "屏幕解锁了");
}
}
}
短信监听
1、InnerActivity#regist
//注册短信广播接收者
IntentFilter smsFilter = new IntentFilter();
smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
mSmsReceiver = new SmsReceiver();
registerReceiver(mSmsReceiver, smsFilter);
2、InnerActivity#onDestroy
unregisterReceiver(mSmsReceiver);//注销短信广播接收者
3、短信广播接收者:SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
//当短信到来的时候 就会执行这个方法
@Override
public void onReceive(Context context, Intent intent) {
//[1]获取发短信送的号码 和内容
Object[] objects = (Object[]) intent.getExtras().get("pdus");
for (Object pdu : objects) {
//[2]获取smsmessage实例
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
//[3]获取发送短信的内容
String body = smsMessage.getMessageBody();
Date date = new Date(smsMessage.getTimestampMillis());//时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//[4]获取发送者
String address = smsMessage.getOriginatingAddress();
String receiveTime = format.format(date);
Log.e("SmsReceiver", "body:" + body + "---" + address+"---"+receiveTime);
}
}
}
4、添加权限
<!--添加权限-->
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
5、安卓5.1,实验结果如下:(6.0以上注意动态权限)
E/SmsReceiver: body:hello---+8613167727310---2018-08-24 21:50:13
后记、
1.声明:
1.本文由张风捷特烈原创,转载请注明
2.欢迎广大编程爱好者共同交流
3.个人能力有限,如有不正之处欢迎大家批评指证,必定虚心改正
4.看到这里,感谢你的喜欢与支持
2.连接传送门:
更多安卓技术欢迎访问:安卓技术栈
我的github地址:欢迎star
张风捷特烈个人网站:http://www.toly1994.com
3.联系我
QQ:1981462002
邮箱:1981462002@qq.com
微信:zdl1994328
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。