在同一个类中发送/接收意图 [英] Send/Receive Intents in the same class

查看:94
本文介绍了在同一个类中发送/接收意图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,是否可以通过LocalBroadcastReceiver在同一类中的send/receive意图?如果可以,可以给我举个例子吗?

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

推荐答案

是的,LocalBroadcastReceiver可以在任何地方使用.这是Activity的示例:

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);
}

在相同的Activity中或应用程序中的其他地方(无关紧要):

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"));

您当然可以使用intent.putExtra添加任何其他数据,或使用多种操作来区分广播消息.

You can, of course, use intent.putExtra to add any additional data or use multiple actions to differentiate broadcast messages.

这篇关于在同一个类中发送/接收意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆