android - 传递 Intent 的上下文

标签 android android-intent broadcastreceiver android-service

我有一个广播接收器,它会启动一个 Intent 服务在一个单独的线程上做一些工作。

我尝试深入研究 Intent 文档以找到一种获取用于创建 Intent 的上下文的方法:

Intent(Context packageContext, Class<?> cls)

但是启动命令的签名如下,不允许您访问传递的上下文。我没有将获取上下文视为 Intent 的公共(public)方法,但我可能错过了一些东西。

public int onStartCommand(Intent intent, int flag, int startId)

有没有一种方法可以获取用于创建 Intent 的上下文,而无需通过第二次广播的路由返回接收器以访问 UI 或处理程序。

最佳答案

I have tried digging into the Intent Documentation to find a way to obtain the context that is used to create the intent

因为 Context 可能不在您的进程中,所以这是不可能的。而且,也没有必要。

Is there a way to get at the context that was used to create the intent without going the route of a second broadcast back the receiver to access the UI

BroadcastReceiver 无法更新 UI。因此,即使您想要的是可能的(实际上不是),它对您也没有好处。

此外,由于您启动的是 IntentService,您可能没有 UI。用户可以控制他们的手机,因此非常欢迎他们离开您的应用并转到主屏幕或其他应用。

处理此问题的一种模式是从 IntentService 发送有序广播。让 Activity 为该广播实现一个高优先级的 BroadcastReceiver,并在 list 中注册一个普通优先级的接收器。后者会引发一个 Notification,因此如果您的 Activity 不在前台,用户将看到 NotificationHere is a blog post更详细一点,here is a sample application演示此技术。

关于android - 传递 Intent 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10882595/

相关文章:

android - onReceive() 不会因传入短信而触发

android - 如何使用 adb 在 Android 11 上触发 BroadcastReceiver?

android - AOSP 构建停止 : subcommand failed

android - 使用路径、路径前缀或路径模式的 Intent 过滤器

java - 错误: constructor intent undefined

java - Android putExtra问题

android - 如何在 Broadcast Receiver 的接收事件中使用倒数计时器?

java - 添加启动画面时,webview URL 未通过 FCM 更新

android - 如何在 RxJava 中链接具有不同间隔的可观察量?

java - 如何使周期性事件在 AsyncTask 的 doInBackground 中的每个周期性间隔运行