开发者

Optimization of service running with a continuously executing TimerTask

I need a service that should always be running till its stopped explicitly by my activity and should start again even if it is stopped due to some issue (START_STICKY flag). This service should continuously do something (every couple of seconds) using a TimerTask. I ended up with the following code.

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);
    }

}

Is there anyway that I can optimiz开发者_运维百科e this to run continuously?


Running every second sounds pretty excessive, but is there a reason why you don't use the AlarmManager to trigger an IntentService? Then the system would be responsible for triggering your service reliably. Whether you can achieve reliable 1 second retriggers, I don't know. Seems like a bad idea for the reasons Mark is mentioning in the other answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜