caipivara
5/28/2015 - 3:49 PM

Android - Timer service to count seconds on background and communicate with [Eventbus](https://github.com/greenrobot/EventBus)

Android - Timer service to count seconds on background and communicate with Eventbus

/**
 * Simple service that use ScheduledExecutorService to count each second and send
 * a SecondLapseEvent on each one with the total time counted.
 *
 * @see SecondLapseEvent
 * @see com.google.common.eventbus.EventBus
 */
public class TimerService extends Service {

    private ScheduledExecutorService executor;
    private int time;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        executor = Executors.newScheduledThreadPool(1);
        time = 0;
        scheduleCount();

        Timber.d("Timer started");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Timber.d("Timer destroyed");
        if (executor != null) {
            executor.shutdown();
        }
        super.onDestroy();
    }


    private void scheduleCount() {
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                time++;
                Timber.d("Timer %d", time);
                BusHelper.post(new SecondLapseEvent(time));
                scheduleCount();
            }
        }, 1, TimeUnit.SECONDS);
    }

}
/**
 * Fired on each second and contains the total of time.
 */
public class SecondLapseEvent {

    private final int mTotalTime;

    public SecondLapseEvent(int time) {
        mTotalTime = time;
    }

    public int getTotalTime() {
        return mTotalTime;
    }

}