4

我想在我的应用程序启动时使用警报管理器来执行重复任务,但是我在取消任务时遇到了问题。

那是我的代码:

服务:

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!

我使用相同的意图来取消任务,即使是相同的实例,但它不起作用。你能帮助我吗?

4

1 回答 1

0

好奇 pintent 是否还在 clear() 中保存 SyncService 的详细信息?

于 2013-07-09T15:43:50.210 回答