gpt4 book ai didi

android - 将上下文传递给 IntentService

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:57 26 4
gpt4 key购买 nike

我有这个代码:

Intent publishIntent = new Intent(HistoryDoneVsPlanned.this, MyIntentService.class);
publishIntent.putExtra(HistoryMap.KEY_WORKOUT_ID, workoutId);

其中 HistoryDoneVsPlanned 是我当前的 Activity,而 MyIntetService 是一个 IntentService。

我的目标是像这样在 intentService 中传递 Activity 的当前上下文:

publishIntent.putExtra("CONTEXT", HistoryDoneVsPlanned.this);

但这是不可能的。

是一种好的做法吗?我需要将 Toast 和通知放入另一个类(不是 Activity)并且我需要 Activity 的上下文。

最佳答案

Is a good practice? I need make the Toast and notification into another class (not Activity) and I need the context of the activity.

没有。这不是一个好的做法。您应该显示来自 Services 的通知。但这取决于您还可以执行的应用程序行为。

情况 1:如果服务/Intent 服务正在后台运行并执行任务..

您应该显示通知而不是 Toast。阅读 How to show notification from background service?

情况 2:如果服务/Intent 服务正在运行并在后台执行任务,但将结果返回到 Activity (这意味着用户在您的应用中)

在这种情况下,您可以显示 Toast。阅读 Show toast at current Activity from service

注意: 并且不要通过 Intent 将上下文传递给 MyIntentService。您也可以通过执行 MyIntentService.thisContext 放入 MyIntentService 中。这是因为所有 Android Components 都覆盖了 Context 类,其中有 IntentService

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

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