Android - Alarm with Wakelock not launching Service from intent

放肆的年华 提交于 2019-12-12 01:14:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!