gpt4 book ai didi

Android - 是否可以在 list 文件中声明本地广播接收器?

转载 作者:行者123 更新时间:2023-11-29 16:57:57 25 4
gpt4 key购买 nike

我已经在我的 list 中声明了我的接收器:

<receiver
android:name=".MyTestReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.ACTION_TEST"/>
</intent-filter>
</receiver>

这是我的 MyTestReceiver 类:

public class MyTestReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

String action = intent.getAction();
if ("com.example.ACTION_TEST".equals(action)) {

Toast.makeText(context, "Test!", Toast.LENGTH_SHORT).show();

}

}
}

但是当我从应用程序中的其他地方执行此代码时:

Intent intent = new Intent("com.example.ACTION_TEST");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

...没有收到本地广播(即没有显示toast)

问题:

  1. 是否可以在 list 中注册本地广播接收器?
  2. 如果是这样,我是否错误地声明了我的本地广播接收器?
  3. 如果无法在 list 中声明本地广播接收器,而是在我的 Application 子类中声明它,它是否与 list 中声明的​​接收器具有相同的“作用域”? (我的意思是,如果它在 list 中声明,它会在所有相同的条件/情况下接收广播吗?)
  4. 如果在 list 中指定接收器与在我的 Application 子类中指定接收器有区别,我是否需要使用一般(非本地)广播而不是本地广播? (在实际应用中,本地广播将在我的 IntentService 完成其工作时发送。IntentService 将由 FCM 推送消息触发。)

注意 - 我似乎可以在 the documentation 中找到所有相关信息是:

Note: To register for local broadcasts, call LocalBroadcastManager.registerReceiver(BroadcastReceiver,
IntentFilter)
instead.

...这没有解决您是否可以在 list 中指定接收者的主要问题。

最佳答案

Is it possible to register a local broadcast receiver in the manifest?

没有。

and I declare it in my Application subclass instead, will it have the same 'scope' as a receiver declared in the manifest? (I mean, will it receive broadcasts in all the same conditions/situations as it would if it was declared in the manifest?)

嗯,不。 list 注册接收器用于系统广播,源自任何进程。 LocalBroadcastManager 是本地的,用于在您自己的进程中“广播”。

欢迎您在 Application 中使用 LocalBroadcastManager 注册接收器(例如,在其 onCreate() 中),但我怀疑无论您要解决什么问题,都有更好的解决方案。

In the actual app, the local broadcast will be sent when my IntentService completes its work

然后接收器应该在需要知道正在完成的工作的 Activity 或 fragment 中注册。您的 Application 不太可能需要知道正在完成的工作,就好像它知道一样,您的 IntentService 可以只调用 Application 上的方法并绕过所有这些广播内容。

关于Android - 是否可以在 list 文件中声明本地广播接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44136409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com