如何使用AlarmManager.setInexactRepeating()使服务保持活动状态?

时间:2016-01-14 12:10:55

标签: android android-intent background-process

我有一些现有的代码会产生一个服务意图,它会在后台运行一堆东西。这段代码确实有用......

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

context.startService(serviceIntent);

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

我已将上述代码更改为:

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 ...

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

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

使用这个新代码,服务永远不会启动,我不明白为什么不。更复杂的是,调试器似乎永远不会及时附加到应用程序以查看正在发生的事情。

谁能看到我做错了什么?

2 个答案:

答案 0 :(得分:2)

将AlarmManager代码放在服务的onDestroy()函数下以安排服务启动,如下所示:

    @Override
        public void onDestroy() {

    /**
             * Flag to restart service if killed.
             * This flag specify the time which is ued by
             * alarm manager to fire action.
             */
            final int TIME_TO_INVOKE = 5 * 1000; // try to re-start service in 5 seconds.

            // get alarm manager
            AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AutoStartServiceReceiver.class);
            PendingIntent pendingIntent = PendingIntent
                .getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            // set repeating alarm.
            alarms.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() +
                    TIME_TO_INVOKE, TIME_TO_INVOKE, pendingIntent);

    }

并在AutoStartServiceReceiver处理服务的启动,如下所示:

public class AutoStartServiceReceiver extends BroadcastReceiver {

    private static final String TAG = AutoStartServiceReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        // check broadcast action whether action was
        // boot completed or it was alarm action.
        if (intent.getAction().equals(AppConstants.ACTION_ALARM_INTENT)) {
            context.startActivity(new Intent(context, YourActivity.class));
            // handle service restart event
            LockerServiceHelper.handleServiceRestart(context);
        }
    }
}

请注意,如果您从设置应用程序正在运行的应用程序(您的应用程序)中手动停止,您的服务将无法重新启动。

答案 1 :(得分:1)

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

如果你想每隔10秒运行一次,请记住上述API 21以下的警报间隔低于60秒会被四舍五入到60秒。

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

相关问题