如何每 5 分钟唤醒一次我的意图服务

how to wake up my intent service every 5 minutes

我知道之前有人问过这个问题,但我没有得到任何答案,我想创建一个意图服务,该服务一直 运行 一个线程,但是当我从应用程序中退出时,我的服务停止然后线程也停止。我需要创建一些东西来每隔几分钟唤醒一次服务。或者即使在应用程序被终止或关闭时也能防止终止服务的东西。

这就是我开始服务的方式

Intent intent= new Intent(Intent.ACTION_SYNC,null,this,IntentServ.class);
startService(intent);

使用正常 Serviceandroid.app.AlarmManager

不需要使用WakefulBroadcastReceiver

为此,您可以使用每 1 小时启动一次服务的 AlarmManager。例如:

 AlarmManager mgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
 Intent notificationIntent = new Intent(context,
                UpdateService.class);
 PendingIntent pendingIntent=PendingIntent.getService(context, requestCode, Intent.parseIntent(), 0);
  mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
        System.currentTimeMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);

AlarmManagerPendingIntent 是您在这种情况下所需要的。 按照下面的例子:

AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);

/* --- 创建待定意图,唤醒时执行 --- */

PendingIntent operation = getUpdatePolicyOperation();
am.set(AlarmManager.RTC, alarmTime, operation); // alarm time is millisecond time in milliseconds that the alarm should go off, using the appropriate clock (depending on the alarm type).

您可以在 AlarmManager 中的 Here or take a tutorial in Here

中阅读有关闹钟模式的更多信息

希望对您有所帮助。