在 IntentService 的 OnHandleIntent 中使用 TimerTask 是一种好习惯吗?

Is it a good practice to use TimerTask in OnHandleIntent in IntentService?

我有一个 IntentService,它使用 TimerTask 每 45 秒调用一次 OnHandleIntent 中的网络服务。

我的问题是: 我正在调用应用程序启动 IntentService,并且在 OnHandleIntent 中,由于 TimerTask,任务不断重复。这样做是一个好习惯还是有任何缺点?我应该在我的 activity 中使用警报管理器来每次调用 Intent 服务,还是可以使用计时器任务在 OnHandleIntent 中继续重复任务?

我的代码是这样的:

 @Override
    protected void onHandleIntent(Intent intent)
    {

        context=this;   //INTENT CONTEXT

        final int timerValue = Integer.parseInt(MainActivitySharedPref.GetValue(context, "serviceTimer"));
        Log.d(TAG, "DOWNLOADSERVICE called having MainActivity.callService as: " + MainActivity.callService);
        t = new Timer();

        task = new TimerTask()
        {

            public void run() {
//run tasks
};
        t.scheduleAtFixedRate(task, 0, timerValue); // service executes task every 45 seconds

谢谢。

Is it a good practice to use TimerTask in OnHandleIntent in IntentService?

绝对不是。

IntentService 旨在让您通过 onHandleIntent() 在提供的后台线程中执行工作。它不是为您创建线程、注册侦听器、设置 TimerTask/ScheduledExecutorService 或执行任何其他 运行 超过 onHandleIntent() 结束而设计的。一旦 onHandleIntent() 结束,IntentService 将自行关闭,之后 Android 可能会在几秒钟内终止您的进程,然后您的后台线程(或者,在本例中,TimerTask)可以做它的工作。

请使用正则Service

should i use an alarm manager in my activity to call the intent service every amount of time or its fine to keep on repeaing the task in OnHandleIntent using the timer task?

如果您只是在您的某些 activity 处于前台时执行此操作,则每 45 秒的部分就可以了。如果您尝试在电池供电的设备上连续执行此操作,请准备好因您造成的电池耗尽而受到用户的攻击。

但是,虽然你的 activity 在前景中...... ScheduledExecutorServiceTimerTask 的现代替代品)在常规 Service 中应该没问题.您不需要 AlarmManager,它专门设计用于在您的进程终止后为您提供更长的轮询周期的控制权。