Android-带有Wakelock的警报无法从意图启动服务 [英] Android - Alarm with Wakelock not launching Service from intent

查看:191
本文介绍了Android-带有Wakelock的警报无法从意图启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,但是让我的Alarm BroadcastReceiver无法启动所需的意图时遇到了一些麻烦。代码如下:

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

调用SetAlarm()时,代码将运行onReceive()并贯穿serviceCode类,它还会设置警报并每1分钟运行一次警报。我发现的问题是,当警报触发并运行唤醒锁时,它没有启动serviceCode并一直运行。相反,它只是忽略了新意图。

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.

注意:唤醒锁在serviceCode的末尾释放。

Note: The wakelock is released at the end of serviceCode.

推荐答案

使用 RTC_WAKEUP 和服务 PendingIntent 是不可靠的。而且,它与您的 onReceive()方法无关。如果想让 BroadcastReceiver 来控制发生警报事件的时间,则需要使用广播 PendingIntent

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.

如果要使用 _WAKEUP 警报,强烈建议您使用 WakefulBroadcastReceiver 我的 WakefulIntentService ,而不是手动滚动自己的 WakeLock 逻辑。

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.

这篇关于Android-带有Wakelock的警报无法从意图启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆