android中本地广播机制,只能在程序内部进行传递。
//发送本地广播
private LocalBroadcastManager localBroadcastManager=LocalBroadcastManager.getInstance(this);
Intent intent=new Intent("com.example.broadcast.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);
我写了一个简单例子
核心代码如下
public class MainActivity extends Activity {
private Button btn_sentbroadcast;
private IntentFilter intentFilter;
private LocalReceiver localReceiver;//自己定义的广播接收者
private LocalBroadcastManager localBroadcastManager;//本地广播管理者
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager=LocalBroadcastManager.getInstance(this);
btn_sentbroadcast=(Button) findViewById(R.id.send_broadcast);
btn_sentbroadcast.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent("com.example.broadcast.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);//发送本地广播
}
});
//注册广播接收者(监听器)
intentFilter=new IntentFilter();
intentFilter.addAction("com.example.broadcast.LOCAL_BROADCAST");
localReceiver=new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}
class LocalReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "接收到本地广播", 5).show();
}
}
}
如果没有看懂请下载我的例子
http://download.csdn.net/detail/zhaihaohao1/8273593