【发布时间】:2017-02-02 12:41:15
【问题描述】:
正如我所读到的,无论您在警报管理器中定义什么时间段,它都会在 sdk 21 之上每 1 分钟触发一次。我正在运行一项服务,我希望我的方法在每 5 分钟后执行一次。这是我做的代码
public class Servicebackground extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("service started in onBind");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = newIntent(this,MyLocationListener.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, pendingIntent);
System.out.println("service started in on create");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("service stopped");
}
@Override
public void onCreate() {
return;
}
public class MyLocationListener extends BroadcastReceiver implements LocationListener {
@Override
public void onReceive(Context context, Intent intent) {
Intent ii = new Intent(context, Servicebackground.class);
startService(ii);
}
在课堂上我正在调用我已经完成的服务
startService(new Intent(this, Servicebackground.class));
但即使我已将时间定义为 5 分钟,该方法也会在每分钟之后运行一次。我读到,在 sdk 21 之后,无论您定义什么时间,如果您使用警报管理器,该方法将在每 1 分钟后执行一次。
如果有任何错误,请告诉我。或者请建议我任何其他方式,即使应用程序被杀死并且该方法每 5 分钟执行一次,我也可以在后台运行服务。如果有其他可能的方式,请建议。
【问题讨论】:
标签: java android service alarmmanager handler