使用连续执行的TimerTask优化服务运行

时间:2011-09-15 19:48:14

标签: android service timer timertask

我需要一个应该一直运行的服务,直到我的活动显式停止它,并且即使由于某些问题(START_STICKY标志)而停止它也应该重新启动。此服务应使用TimerTask持续执行某些操作(每隔几秒钟)。我最终得到了以下代码。

public class SomeService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    TimerTask timerTask;
    final Handler handler = new Handler();
    Timer timer = new Timer();

    @Override
    public void onCreate() {
        // code to execute when the service is first created
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        // code to execute when the service is shutting down
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        // code to execute when the service is starting up
        timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                                   //KEEP RUNNING SOME ERRANDS HERE
                        }
                    }
                });
            }
        };
        timer.scheduleAtFixedRate(timerTask, 100L, 1700L);
    }

}

无论如何,我可以优化它以持续运行吗?

1 个答案:

答案 0 :(得分:6)

每秒运行听起来相当多,但是有没有理由不使用AlarmManager来触发IntentService?然后系统将负责可靠地触发您的服务。你是否可以实现可靠的1秒重击,我不知道。由于Mark在另一个答案中提到的原因,似乎是一个坏主意。

相关问题