我使用一个AlarmManager来触发一个广播信号的意图。以下是我的代码:

AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, Wakeup.class);
try
{
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
    Long elapsed +=  // sleep time;
    mgr.set(AlarmManager.RTC_WAKEUP, elapsed, pi);
}
catch(Exception r)
{
    Log.v(TAG, "RunTimeException: " + r);
}

我从一个活动调用这个代码,所以我不知道我如何得到以下错误…

ERROR/AndroidRuntime(7557): java.lang.RuntimeException: Unable to start receiver com.wcc.Wakeup: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

当前回答

对于同一个活动的多个实例,使用下面的代码段,

注意:这个片段,我在我的活动之外使用。确保你的AndroidManifest文件不包含android:launchMode="singleTop|singleInstance"。如果需要,你可以把它改成android:launchMode="standard"。

Intent i = new Intent().setClass(mActivity.getApplication(), TestUserProfileScreenActivity.class);  
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

// Launch the new activity and add the additional flags to the intent
mActivity.getApplication().startActivity(i);

这对我来说很好。霍普,这为别人节省了时间。如果有人找到更好的方法,请与我们分享。

其他回答

我在最新的Android设备9和10上收到通知时也遇到过同样的错误。

这取决于你如何处理它的启动模式。使用以下代码:- android: launchMode = " singleTask "

添加此标志与意图:- intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);

我只是想注意,startActivity从一个活动之外是有效的在一些android版本(在N和O-MR1之间),有趣的是,这是一个漏洞在android源代码!

这是startActivity实现上面的注释。在这里看到的。

在没有FLAG_ACTIVITY_NEW_TASK的情况下从活动外部调用启动活动 通常不允许,除非调用者指定了活动应该使用的任务id 发射。在N和O-MR1之间存在一个错误,这允许它工作。

对于同一个活动的多个实例,使用下面的代码段,

注意:这个片段,我在我的活动之外使用。确保你的AndroidManifest文件不包含android:launchMode="singleTop|singleInstance"。如果需要,你可以把它改成android:launchMode="standard"。

Intent i = new Intent().setClass(mActivity.getApplication(), TestUserProfileScreenActivity.class);  
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

// Launch the new activity and add the additional flags to the intent
mActivity.getApplication().startActivity(i);

这对我来说很好。霍普,这为别人节省了时间。如果有人找到更好的方法,请与我们分享。

如果你的android版本低于android - 6,那么你需要添加这一行,否则它将在android - 6之上工作。

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...

在我的情况下,我已经使用context的startActivity,改变后与ActivityName。这一点。它解决了。我使用的是来自util类的method。

希望它能帮助到一些人。