我遇到了警报管理器的问题。我不想每小时执行一次我的服务。 警报管理器在重新启动后启动并运行良好,即使应用程序未打开或打开和关闭(My PhoneStartReceiver在完成启动后调用launchBackgroundService一次)。 我的问题是我在安装后启动应用程序,没有重启电话。在这种情况下,当应用程序强制关闭或销毁时,AlarmManager将被终止。
安装和下次重启之间存在问题。如何在下次重启之前保持启用AlarmManager?
<receiver
android:name=".helpers.PeriodicalServiceCaller"
android:process=":remote"/>
<receiver
android:name=".helpers.PhoneStartReceiver"
android:process=":remote">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
这是我的launchBackgroundServiceMethod,在两种情况下均会被调用。
public static void launchBackgroundService(){
// Construct an intent that will execute the PeriodicalServiceCalle
Intent intent = new Intent(getApplicationContext(), PeriodicalServiceCaller.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), PeriodicalServiceCaller.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every minute
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 1000L, pIntent);
}
PeriodicallServiceCaller代码
public class PeriodicalServiceCaller extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {
Log.i("START-SERVICE", "PeriodicalServiceCaller");
Intent i = new Intent(context, MonitorDataService.class);
context.startService(i);
}
修改 我的launchBackgroundService是在安装后由Acitivity启动的,如果是在重新启动后由PhoneStartReceiver启动的
答案 0 :(得分:0)
您需要注册BroadcastReceiver
以检测您的更新时间。
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
看看
How to know my Android application has been upgraded in order to reset an alarm?
答案 1 :(得分:0)
是在服务中运行launchBackgroundService还是从活动中运行?如果是从服务运行,请检查此答案Background Service getting killed in android
START_STICKY是我错过的。