Send/Receive Intents in the same class

蹲街弑〆低调 提交于 2019-12-08 10:47:27

问题


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.



来源:https://stackoverflow.com/questions/15316361/send-receive-intents-in-the-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!