如何使用AlarmManager.setInexactRepeating()使服务保持活动状态? [英] How to keep a service alive using AlarmManager.setInexactRepeating()?

查看:531
本文介绍了如何使用AlarmManager.setInexactRepeating()使服务保持活动状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些现有的代码,它们产生了一个服务意图,该服务意图在后台执行了很多工作.该代码确实有效...

I have some existing code that spawns a service intent which does a bunch of stuff in the background. This code does work...

Intent serviceIntent = new Intent(context, APMService.class);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startService(serviceIntent);

我的问题是:如何更改它以使用AlarmManager.setInexactRepeating(...)方法?

My question is: how to change this to use the AlarmManager.setInexactRepeating(...) methods?

我已将上面的代码更改为此:

I have changed the above code to this:

Intent serviceIntent = new Intent(context, APMService.class);
serviceIntent.putExtra("STARTED_BY", starter);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//Set up recurring alarm that restarts our service if
// it crashes or if it gets killed by the Android OS
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, serviceIntent, 0);
//am.cancel(pi);

am.setInexactRepeating(
        AlarmManager.ELAPSED_REALTIME_WAKEUP    //wake up the phone if it's asleep
        , cal.getTimeInMillis()
        , 10000
        , pi);

并且我已将这些权限添加到AndroidManifest.xml ...

And I have added these permissions to AndroidManifest.xml...

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="com.android.alarm.permission.WAKE_LOCK"/>

我的理解是,这应该立即启动服务,然后尝试每10秒重新启动一次.但是此代码无法正常工作.

My understanding is that this is supposed to start the service immediately and then try to restart it again every 10 seconds. But this code isn't working properly.

使用此新代码,该服务根本无法启动,我不明白为什么不这样做.使事情变得复杂的是,调试器似乎从来没有及时附加到应用程序上以查看发生了什么情况.

Using this new code, the service never starts at all and I cannot see why not. To complicate matters the debugger never seems to attach to the app in time to see what's going on.

任何人都可以看到我在做什么吗?

Can anyone see what I'm doing wrong?

推荐答案

由于AlarmManager.ELAPSED_REALTIME_WAKEUP,您的服务未启动,而应该使用AlarmManager.RTC_WAKEUP

Your service is not starting because of AlarmManager.ELAPSED_REALTIME_WAKEUP, while it should be using AlarmManager.RTC_WAKEUP

如果要每10秒运行一次,请记住,高于API 21的警报间隔低于60s会向上舍入为60s.

If you want to run every 10s keep in mind that above API 21 alarm intervals below 60s are rounded up to 60s.

另外,请考虑使用WakefulIntentService https://github.com/commonsguy/cwac-wakeful

这篇关于如何使用AlarmManager.setInexactRepeating()使服务保持活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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