Send/Receive Intents in the same class

2019-06-14 06:14发布

Simple question, Is it possible to send/receive intents in the same class through LocalBroadcastReceiver? If yes can you show me an example?

1条回答
仙女界的扛把子
2楼-- · 2019-06-14 06:30

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.

查看更多
登录 后发表回答