Calling startActivity() from outside of an Activit

2019-01-03 04:57发布

I'm using an AlarmManager to trigger an intent that broadcasts a signal. The following is my code:

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);
}

I'm calling this code from an Activity, so I don't know how I could be getting the following error...

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?

8条回答
forever°为你锁心
2楼-- · 2019-01-03 05:25

What if you add this line:

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
查看更多
Fickle 薄情
3楼-- · 2019-01-03 05:32

instead of application context(i.e.getApplication(); getApplicationContext(); ) you need to use Activity Context in this case ---> YourActivity.this

查看更多
登录 后发表回答