我想使用Alarm Manager在我的应用程序启动时执行重复任务,但是我在取消任务时遇到问题。
这是我的代码:
服务:
public class SyncService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("#####", "It's alive!");
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
应用:
public class TerminalApplication extends Application {
PendingIntent pintent;
AlarmManager alarm;
@Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, SyncService.class);
pintent = PendingIntent.getService(this, 0, intent, 0);
alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Log.e("#####", "Starting alarm");
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), 5 * 1000, pintent);
}
@Override
public void onTerminate() {
clear();
super.onTerminate();
}
public void clear() {
alarm.cancel(pintent);
Log.e("#####", "Alarm cancelled");
}
}
这就是我在日志中看到的内容:
07-09 14:53:30.399: ERROR/#####(1743): Starting alarm
07-09 14:53:52.690: ERROR/#####(1590): It's alive!
07-09 14:54:02.690: ERROR/#####(1590): It's alive!
07-09 14:54:12.690: ERROR/#####(1590): It's alive!
07-09 14:54:20.475: ERROR/#####(1743): Alarm cancelled
07-09 14:54:22.695: ERROR/#####(1590): It's alive!
07-09 14:54:32.696: ERROR/#####(1590): It's alive!
我使用相同的意图取消任务,即使是同一个实例,但它不起作用。你能救我吗?
答案 0 :(得分:0)