broadcast在整个实际开发中,也是一个比较常用的一个操作。
广播有无序广播和有序广播。但是在笔者经理的项目中常见的是无序广播。
广播的注册有两类:一个是静态广播,一个是动态广播。简单的说是xml与register广播。
广播有两个操作,一个是发广播的,一个是收广播的。一般来说,我们是关注收广播去做啥事情。
简单举一个例子:
<receiver android:name=".XXXXXXXX" >
<intent-filter android:priority="255">
<action android:name="android.intent.action.MAIN"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
那么这个广播接受者:android.intent.action.BOOT_COMPLETED设计的是一个开机完成的广播。
public class XXXXReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent starterIntent = new Intent(context, XXXX.class);
starterIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
starterIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(starterIntent);
};
}
设计了一个很简单的功能,就是开机后,进入到应用的某一个操作。
当然在这里简单拓展一下,在现在实际的一些应用中,很多都开始添加私有权限,避免数据被拦截。保护数据的安全性。
下面介绍的一个动态使用的广播:
pushResultReceiver = new PushResultReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("xxxx"); intentFilter.addAction("yyyyyy"); registerReceiver(pushResultReceiver, intentFilter);
public class PushResultReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { LogUtils.showLog("receive broadcast action = " + intent.getAction()); if (intent.getAction().equals("XXXXXX")) { String s = intent.getStringExtra("result"); if (StartupUtil.isApplicationAlive) { String user_id = sp.GetString("id", ""); try { JSONObject jsonObject = new JSONObject(s); String push_id = jsonObject.getString("user_id"); if (push_id.equals(user_id)) { } else { sp.KeepString("push_result", s); } } if (intent.getAction().equals("YYYYYY")) { sp.KeepString("bd_user_id", intent.getStringExtra("bd_user_id")); sp.KeepString("bd_channel_id", intent.getStringExtra("bd_channel_id")); } } }
使用的发送者:Intent intent = new Intent(); bundle.putString("result", s); intent.setAction("XXXXX"); intent.putExtras(bundle); context.sendBroadcast(intent);
很多开发人员经常,只有registerReceiver,没有写unRegisterReceiver(),如果是频繁使用,可能会造成,广播泄露。
笔者曾经就被坑过,具体的是哪一个项目,年代久远已经忘记了。找了一个项目中,有的一个写法给大家展示一下:
@Override
protected void onResume() {
// TODO Auto-generated method stub
RefreshUI();
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(mReceiver);
}
由于找这个代码,笔者搜索了一下某个工程的源码:当前使用的AS已经有三个项目了,怕系统抗不住。就是用了sublime这个编辑。这个也推荐给大家使用。
搜索源码还是比较方便的。快捷键网上有大家使用的時候自己去搜索。我刚使用ctr+shift+F一個全局搜索。簡單找了這麼一個例子。
這裡有一些還沒有去讲,也欢迎大家留言讨论:
比如:动静态广播应用场景还有他们的区别?