Simple question, Is it possible to send/receive
intents in the same class through LocalBroadcastReceiver
? If yes can you show me an example?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Yes, LocalBroadcastReceiver works everywhere. Here's an example for an Activity
:
BroadcastReceiver localBroadcastReciever = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.d("BroadcastReceiver", "Message received " + intent.getAction());
}
};
@Override
protected void onStart()
{
super.onStart();
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(this);
final IntentFilter localFilter = new IntentFilter();
localFilter.addAction("com.my.package.intent.ACTION_NAME_HERE");
localBroadcastManager.registerReceiver(localBroadcastReceiver, localFilter);
}
@Override
protected void onStop()
{
super.onStop();
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(this);
// Make sure to unregister!!
localBroadcastManager.unregisterReceiver(localBroadcastReceiver);
}
Somewhere, either in the same Activity
or elsewhere in your application (it doesn't matter):
final LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(context);
localBroadcastManager.sendBroadcast(new Intent("com.my.package.intent.ACTION_NAME_HERE"));
You can, of course, use intent.putExtra
to add any additional data or use multiple actions to differentiate broadcast messages.