【问题标题】:'startactivity called from non-activity context service' warning when launching intent from notification从通知启动意图时的“从非活动上下文服务调用的启动活动”警告
【发布时间】:2013-12-02 01:32:48
【问题描述】:

我有一个 service,它以 notification 开头,startForeground(),我希望通知在点击时启动一个活动。
我要启动的acitivty 定义为android:launchMode="singleTask",通常在服务启动之前运行。
这是我的pending intent 创建代码:

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

当我点击通知时,我收到以下警告:

startActivity called from non-Activity context; 
forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent........

我也尝试使用 this 而不是 getApplicationContext() 获取活动,但收到了相同的警告。
我应该如何做到这一点?

【问题讨论】:

  • 这毫无意义。您拥有的代码绝对没问题,不应产生您看到的错误消息。

标签: android android-intent service notifications android-pendingintent


【解决方案1】:

不要将Intent.FLAG_ACTIVITY_NEW_TASK 用于PendingIntent.getActivity。最好使用FLAG_ONE_SHOT

并尝试使用ContextActivity 而不是getApplicationContext()

【讨论】:

  • 即使我从service 打来电话,也要使用activity context 吗?我应该为此保存服务activity 创建者上下文吗?
  • 先尝试修复FLAG_ONE_SHOT。
  • 我做了,效果很好。谢谢。但是不正确的上下文呢?
  • 如果你使用PendingIntent.getActivity(),并且你在Service中使用这个PendingIntent,或者把它放在Notification中,你必须设置Intent.FLAG_ACTIVITY_NEW_TASK。如果你不这样做,Android 会发出警告并为你设置标志,但我只是 Android 很好。
  • 当您像这样调用Intent 构造函数时使用Context 绝对没有区别:new Intent(Context, Activity.class)。本例中的Context仅用于获取组件的包名
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
相关资源
最近更新 更多