问题
I am writing an app and am having a bit of trouble with getting my Alarm BroadcastReceiver from starting a desired intent. The code is as follows:
public void onReceive(Context context, Intent intent)
{
Log.d("Alarm:","Running WakeLock");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
WakeMe.wakelock = wl;
Log.d("Alarm:","Running Intent (Service)");
Intent i = new Intent(context, serviceCode.class);
context.startService(i);
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getService(context, 1, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, pi); // Millisec * Second * Minute
Log.d("Alarm:", "Alarm set to run every 1 minute/s");
}
When SetAlarm() is called the code runs the onReceive() and runs through serviceCode class, it also sets the alarm up and runs the alarm every 1 minute. The problem i am finding is that when the alarm fires and runs the wakelock it is not starting serviceCode and running through. Instead it just ignores the new intent.
Note: The wakelock is released at the end of serviceCode.
Any help would be apreciated
回答1:
Using RTC_WAKEUP
with a service PendingIntent
, as you are doing here, is unreliable. Moreover, it would have nothing to do with your onReceive()
method. You need to use a broadcast PendingIntent
if you want a BroadcastReceiver
to get control when the alarm event occurs.
If you want to use a _WAKEUP
alarm, I strongly suggest that you use WakefulBroadcastReceiver or my WakefulIntentService, rather than hand-rolling your own WakeLock
logic.
来源:https://stackoverflow.com/questions/21410210/android-alarm-with-wakelock-not-launching-service-from-intent