android - 如何从 BroadcastReceiver 启动一项 Activity ?

标签 android android-intent android-activity broadcastreceiver

我有一个广播接收器(c2dm 推送接收器)。 当我收到推送时,我希望发生这种情况:

  • 启动通知,您将被引导至 StopAlarmActivity(完成!)
  • 如果应用程序在前面,启动 StopAlarmActivity(我如何检查)

我的主要问题是我无法让广播接收器为我启动 StopAlarmActivity。

我已经在 list 中注册了广播接收器。

这是我用来尝试启动 Activity 的代码:

Intent intentHome = new Intent(context, StopAlarmActivity.class);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(intentHome);

这是堆栈跟踪消息:

11-20 00:29:30.514: E/AndroidRuntime(13612): java.lang.RuntimeException: Unable to start receiver com.packagename.PushReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

我看到有人说它只是在 Intent 中添加 FLAG_ACTIVITY_NEW_TASK,异常也告诉我,所以我真的不明白为什么它不起作用。

有人知道吗? 提前致谢!

最佳答案

在你的代码中你有:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

但您对这个新 Activity 的 Intent 是 intentHome。将该行更改为:

intentHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

关于android - 如何从 BroadcastReceiver 启动一项 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8198245/

相关文章:

Android VideoView 根据每个设备调整大小

java - 通过 XML 从 android 发送图像

Android:将搜索查询转发到一个处理搜索的 Activity

android - 最小化应用程序、更改语言并恢复调用 onCreate() 而不是 onResume()

android - 一个 Activity 的两个发射器

android - Robolectric 无法下载连接超时

java - 使用 Span 在 android EditText 上突出显示语法?

android - java.lang.IllegalArgumentException : Service Intent must be explicit: Intent

android - 在 Android 中的导航堆栈顶部启动 Activity

android - 从 Android 应用程序打开文件管理器