我使用一个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);
这对我来说很好。霍普,这为别人节省了时间。如果有人找到更好的方法,请与我们分享。
对于同一个活动的多个实例,使用下面的代码段,
注意:这个片段,我在我的活动之外使用。确保你的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 Doc”
FLAG_ACTIVITY_NEW_TASK requirement is now enforced
With Android 9, you cannot start an activity from a non-activity
context unless you pass the intent flag FLAG_ACTIVITY_NEW_TASK. If you
attempt to start an activity without passing this flag, the activity
does not start, and the system prints a message to the log.
Note: The flag requirement has always been the intended behavior, and
was enforced on versions lower than Android 7.0 (API level 24). A bug
in Android 7.0 prevented the flag requirement from being enforced.
这意味着for (Build.VERSION)。SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION. m)SDK_INT >= Build.VERSION_CODES.P)必须添加Intent。FLAG_ACTIVITY_NEW_TASK在Activity上下文外部调用startActivity()时。
所以最好为所有版本添加标记-
...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...