Android LocalBroadCastManager简介
2016-08-05 20:59
295 查看
LocalBroadCastManager也是广播的一种,但不同的是BroadCastReceiver用于不同进程间通信,总体来说适用于安全性要求不太高的数据传递,而LocalBroadCastManager适用于应用内部的信息传递,又称之为局部通知管理器。
LocalBroadCastManager在android-support-v4.jar(这个相信大家都不陌生)中引入,有效率高,安全性高,可代替Thread与Handle组合刷新UI等优点。
LocalBroadCastManager在android-support-v4.jar(这个相信大家都不陌生)中引入,有效率高,安全性高,可代替Thread与Handle组合刷新UI等优点。
示例代码: public class MainActivity extends Activity { /** * 定义三个Action状态 */ static final String ACTION_STARTED = "com.example.android.supportv4.STARTED"; static final String ACTION_UPDATE = "com.example.android.supportv4.UPDATE"; static final String ACTION_STOPPED = "com.example.android.supportv4.STOPPED"; LocalBroadcastManager mBroadCastManager; BroadcastReceiver mBroadCastReceiver; TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init(){ mTextView = (TextView) this.findViewById(R.id.showText); mBroadCastManager = LocalBroadcastManager.getInstance(this); IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_STARTED); filter.addAction(ACTION_UPDATE); filter.addAction(ACTION_STOPPED); mBroadCastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(ACTION_STARTED)){ mTextView.setText("Start !"); } else if(intent.getAction().equals(ACTION_UPDATE)){ mTextView.setText(intent.getExtras().get("update").toString()); } else if(intent.getAction().equals(ACTION_STOPPED)){ mTextView.setText("Stoppppp !"); } } }; /** * 注册LocalBroadCastManager */ mBroadCastManager.registerReceiver(mBroadCastReceiver,filter); /** * 开启线程传递数据 */ new Thread(new Runnable() { @Override public void run() { Intent myIntent = new Intent(ACTION_UPDATE); myIntent.putExtra("update","LaLaLa"); mBroadCastManager.sendBroadcast(myIntent); } }).start(); } @Override protected void onStop() { super.onStop(); /** * 取消LocalBroadCastManager */ mBroadCastManager.unregisterReceiver(mBroadCastReceiver); } }
相关文章推荐
- Android中BroadcastReceiver(异步接收广播Intent)的使用
- Android使用BroadcastReceiver实现手机开机之后显示画面的功能
- Android提高之BroadcastReceiver实例详解
- 详解Android中BroadCastReceiver组件
- Android采取BroadcastReceiver方式自动获取验证码
- Android编程四大组件之BroadcastReceiver(广播接收者)用法实例
- Android开发之BroadcastReceiver用法实例分析
- 广播 BroadCastReceiver
- BroadcastReceiver应用详解
- Android中利用广播接受者简单几步实现拨号显示归属地
- 拦截短信
- Android中BroadcastReceiver理解
- 关于安卓手机开机自启动APP无法成功的问题
- Android开发学习之路 -- 关于BroadcastReceiver
- android 监听SDCard安装和卸载的代码
- BroadcastReceiver实现android来去电录音功能(外录)
- 小米手机不支持对去电的拦截解决方案(BroadcastReceiver)
- BroadcastReceiver之开机自启动程序
- 工作笔记(1)--Android平板禁用虚拟按键