Skip to content

Instantly share code, notes, and snippets.

@blazorin
Created December 12, 2023 12:29
Show Gist options
  • Save blazorin/b7bafad514470df4a133859ba0f2aac5 to your computer and use it in GitHub Desktop.
Save blazorin/b7bafad514470df4a133859ba0f2aac5 to your computer and use it in GitHub Desktop.
ClockService
package com.albertoromero.timeclock.services;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.albertoromero.timeclock.utils.NotificationUtils;
public class ClockService extends Service {
public static final String ACTION_START_TIMER = "action.START_TIMER";
public static final String ACTION_PAUSE_TIMER = "action.PAUSE_TIMER";
public static final String ACTION_RESET_TIMER = "action.RESET_TIMER";
public static final String TIMER_UPDATE_ACTION = "action.TIMER_UPDATE";
public static final String EXTRA_TIME_LEFT = "EXTRA_TIME_LEFT";
public static final String EXTRA_TIME = "EXTRA_TIME";
private final Handler handler = new Handler();
private long timeLeftInMillis;
private boolean isTimerRunning;
private long defaultTimeMilis = 60 * 1000;
private final Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (isTimerRunning) {
timeLeftInMillis -= 1000;
if (timeLeftInMillis <= 0) {
isTimerRunning = false;
NotificationUtils.showNotification("Time's up!", "Time's up!");
}
// Broadcast time left
broadcastTimeLeft();
if (isTimerRunning) {
handler.postDelayed(this, 1000);
}
}
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
if (ACTION_START_TIMER.equals(action)) {
long time = intent.getLongExtra(EXTRA_TIME, defaultTimeMilis);
startTimer(timeLeftInMillis > 0 ? timeLeftInMillis : time);
} else if (ACTION_PAUSE_TIMER.equals(action)) {
pauseTimer();
} else if (ACTION_RESET_TIMER.equals(action)) {
long time = intent.getLongExtra(EXTRA_TIME, defaultTimeMilis);
resetTimer(time);
}
}
return START_STICKY;
}
private void startTimer(long timeInMillis) {
if (isTimerRunning) return;
this.timeLeftInMillis = timeInMillis;
this.isTimerRunning = true;
handler.post(timerRunnable);
}
private void pauseTimer() {
isTimerRunning = false;
}
private void resetTimer(long timeInMillis) {
this.timeLeftInMillis = timeInMillis;
isTimerRunning = false;
broadcastTimeLeft();
}
private void broadcastTimeLeft()
{
Intent intent = new Intent(TIMER_UPDATE_ACTION);
intent.putExtra(EXTRA_TIME_LEFT, timeLeftInMillis);
LocalBroadcastManager.getInstance(ClockService.this).sendBroadcast(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(timerRunnable);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment