سؤال

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 optimize 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top