Android四大组件之一BroadcastReceiver简析
最近有在温故知新,故将自己的一些浅薄见解归纳总结,供各位参考,也方便自己日后查阅。
BroadcastReceiver是一个全局监听器,可用来实现系统不同组件之间的通信(关于BroadcastReceiver的详细定义在此不再赘述)。
BroadcastReceiver按性质可分为:A、系统广播,如电量、短信等;B、开发人员的自定义广播;
按方式可分为:A、无序广播(普通广播);B、有序广播;C、粘性广播;
其中有序广播与无序广播的流程均为:1、注册;2、发送;3、接收。
广播按注册方式可分为:①、静态注册;②、动态注册。
不论静态注册或动态注册均需自建Java类extends BroadcastReceiver。
以下为代码示例:
A、无序广播
一、静态注册广播
/**
* Created by shiyuan on 2017/7/26.
* 静态注册--广播接收者实现
*/
public class ShayeReceiver extends BroadcastReceiver {
private String TAG = this.getClass().getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String result = intent.getStringExtra("key");
Log.d(TAG,"静态广播"+"action:"+action+" ..... 广播传送的内容: "+result);
Toast.makeText(context,"静态广播",Toast.LENGTH_SHORT).show();
}
}
/**
*清单文件 --- 静态广播注册
*/
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.shangpay.shayeimprovebasic">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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=".myreceiver.ShayeReceiver">
<intent-filter>
<action android:name="static_Broadcast"></action>
</intent-filter>
</receiver>
</application>
</manifest>
二、动态注册广播
/**
*动态广播注册
*/
public class MainActivity extends AppCompatActivity {
private String TAG = this.getClass().getSimpleName();
private ShayeActionBroadReceiver actionBroadReceiver; //动态注册广播
private IntentFilter intentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
this.actionBroadReceiver = new ShayeActionBroadReceiver();
this.intentFilter = new IntentFilter();
this.intentFilter.addAction("actionBroad");
// 有序广播
this.orderBroadCastReciverFirst = new OrderBroadCastReciverFirst();
this.filterFirst = new IntentFilter("order");
this.filterFirst.setPriority(100);
this.orderBroadCastReciverSecond = new OrderBroadCastReciverSecond();
this.filterSecond = new IntentFilter("order");
this.filterSecond.setPriority(50);
}
@Override
protected void onResume() {
super.onResume();
/**
* 动态广播 ---注册广播
*/
// LocalBroadcastManager.getInstance(this).registerReceiver(actionBroadReceiver,intentFilter);
this.registerReceiver(actionBroadReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//销毁广播接收者
this.unregisterReceiver(actionBroadReceiver);
}
/**
*动态广播接收者
*/
private class ShayeActionBroadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "动态广播接收", Toast.LENGTH_SHORT).show();
String action = intent.getAction();
String result = intent.getStringExtra("actionKey");
Log.d(TAG, "action:" + action + " ...result:" + result);
}
}
B、有序广播
有序广播注册方式与无序广播注册方式一样,以下以动态注册为例:
public class MainActivity extends AppCompatActivity {
private String TAG = this.getClass().getSimpleName();
private OrderBroadCastReciverFirst orderBroadCastReciverFirst; // 有序广播
private OrderBroadCastReciverSecond orderBroadCastReciverSecond;
private IntentFilter filterFirst;
private IntentFilter filterSecond;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// 有序广播
this.orderBroadCastReciverFirst = new OrderBroadCastReciverFirst();
this.filterFirst = new IntentFilter("order");
this.filterFirst.setPriority(100);
this.orderBroadCastReciverSecond = new OrderBroadCastReciverSecond();
this.filterSecond = new IntentFilter("order");
this.filterSecond.setPriority(50);
}
@Override
protected void onResume() {
super.onResume();
/**
* 有序广播 ---动态注册
*/
this.registerReceiver(orderBroadCastReciverFirst,filterFirst);
this.registerReceiver(orderBroadCastReciverSecond,filterSecond);
}
@Override
protected void onDestroy() {
super.onDestroy();
//销毁广播接收者
this.unregisterReceiver(orderBroadCastReciverSecond);
this.unregisterReceiver(orderBroadCastReciverFirst);
}
/**
*发送有序广播
*/
@OnClick(R.id.button_orderBroad)
void buttonClick(View view) {
switch (view.getId()) {
case R.id.button_orderBroad:
Intent orderIntentOne = new Intent("order");
orderIntentOne.putExtra("order1", "有序广播-----1");
sendOrderedBroadcast(orderIntentOne, null);
break;
}
}
/**
*有序广播接收者
*/
private class OrderBroadCastReciverFirst extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String result = intent.getStringExtra("order1");
Log.d(TAG,"有序广播1,action:"+action+" ...result:"+result);
Bundle bundle = new Bundle();
bundle.putString("order2","333333来自有序广播1的处理结果");
intent.putExtra("bundle",bundle);
setResultExtras(bundle);
//切断广播,不再让广播发送
//abortBroadcast();
}
}
private class OrderBroadCastReciverSecond extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"有序广播2");
String action = intent.getAction();
String result = intent.getStringExtra("order1");
Bundle h = getResultExtras(true);
Log.d(TAG,"action:"+action+"\nresult:"+result+"\n有序广播1的处理结果:"+h.getString("order2")
+"\nBundle:"+intent.getExtras().toString());
}
}
C、粘性广播
1、需在清单文件AndroidManifest.xml中添加 权限
<uses-permission android:name="android.permission.BROADCAST_STICKY"></uses-permission>
2、粘性广播的调用方法:sendStickyBroadcast(intent1),其他均一样;
3、一般广播都是先注册广播,才能接收到广播,而粘性广播可以做到先发送广播,哪里需要接收该广播就哪里注册,可以后注册广播拿到广播的结果。这就是 普通广播和粘性广播的区别。从示例中也看出了普通广播在跳转到ReceiveActivity中是接受不到广播发送者发出的广播的,只有粘性广播才能接收到。
在此就不贴代码了。敬请谅解
此处代码为MainActivity,为了省事,将静态注册、动态注册以及有序广播均写在了这个Activity中。
public class MainActivity extends AppCompatActivity {
private String TAG = this.getClass().getSimpleName();
private String staticAction = "static_Broadcast";
private ShayeActionBroadReceiver actionBroadReceiver; //动态注册广播
private IntentFilter intentFilter;
private OrderBroadCastReciverFirst orderBroadCastReciverFirst; // 有序广播
private OrderBroadCastReciverSecond orderBroadCastReciverSecond;
private IntentFilter filterFirst;
private IntentFilter filterSecond;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
this.actionBroadReceiver = new ShayeActionBroadReceiver();
this.intentFilter = new IntentFilter();
this.intentFilter.addAction("actionBroad");
// 有序广播
this.orderBroadCastReciverFirst = new OrderBroadCastReciverFirst();
this.filterFirst = new IntentFilter("order");
this.filterFirst.setPriority(100);
this.orderBroadCastReciverSecond = new OrderBroadCastReciverSecond();
this.filterSecond = new IntentFilter("order");
this.filterSecond.setPriority(50);
}
@Override
protected void onResume() {
super.onResume();
/**
* 动态广播 ---注册广播
*/
// LocalBroadcastManager.getInstance(this).registerReceiver(actionBroadReceiver,intentFilter);
this.registerReceiver(actionBroadReceiver, intentFilter);
this.registerReceiver(orderBroadCastReciverFirst,filterFirst);
this.registerReceiver(orderBroadCastReciverSecond,filterSecond);
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(actionBroadReceiver);
this.unregisterReceiver(orderBroadCastReciverSecond);
this.unregisterReceiver(orderBroadCastReciverFirst);
}
@OnClick({R.id.button_test, R.id.button_actionBroad, R.id.button_orderBroad})
void buttonClick(View view) {
switch (view.getId()) {
case R.id.button_test:
Intent broadIntent = new Intent(staticAction);
broadIntent.putExtra("key", "静态广播测试。。。。");
this.sendBroadcast(broadIntent);
break;
case R.id.button_actionBroad:
Intent actionBroadIntent = new Intent();
actionBroadIntent.setAction("actionBroad");
actionBroadIntent.putExtra("actionKey", "KKKKK。。。动态广播注册。。。");
this.sendBroadcast(actionBroadIntent);
break;
case R.id.button_orderBroad:
Intent orderIntentOne = new Intent("order");
orderIntentOne.putExtra("order1", "有序广播-----1");
sendOrderedBroadcast(orderIntentOne, null);
break;
}
}
private class ShayeActionBroadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "OOPPPP", Toast.LENGTH_SHORT).show();
String action = intent.getAction();
String result = intent.getStringExtra("actionKey");
Log.d(TAG, "action:" + action + " ...result:" + result);
}
}
private class OrderBroadCastReciverFirst extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String result = intent.getStringExtra("order1");
Log.d(TAG,"有序广播1,action:"+action+" ...result:"+result);
Bundle bundle = new Bundle();
bundle.putString("order2","333333来自有序广播1的处理结果");
intent.putExtra("bundle",bundle);
setResultExtras(bundle);
//切断广播,不再让广播发送
//abortBroadcast();
}
}
private class OrderBroadCastReciverSecond extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"有序广播2");
String action = intent.getAction();
String result = intent.getStringExtra("order1");
Bundle h = getResultExtras(true);
Log.d(TAG,"action:"+action+"\nresult:"+result+"\n有序广播1的处理结果:"+h.getString("order2")
+"\nBundle:"+intent.getExtras().toString());
}
}
}
终:这是我看到的关于广播写得较好的文章,本文中关于粘性广播的总结摘抄自此处:http://blog.csdn.net/feiduclear_up/article/details/45720675。