I was wondering, in Android, I have a service that holds a timer since connecting to a BLE device. I would like the service to stay bound until either the device disconnects or until the entire app is closed. I do not want the service to be stopped while navigating between activities.
Here is my Service code:
public class TimerService extends Service {
private static String LOG_TAG = "TimerService";
private IBinder mBinder = new MyBinder();
Handler onlineTimeHandler;
long startTime = 0L, timeInMilliseconds = 0L, timeSwapBuff = 0L, updatedTime = 0L;
int mins, secs, hours;
String time = "";
private HandlerThread mHandlerThread = new HandlerThread("TimerHandler");
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
Log.v(LOG_TAG, "in onCreate");
mHandlerThread.start();
onlineTimeHandler = new Handler(mHandlerThread.getLooper());
startTime = SystemClock.uptimeMillis();
onlineTimeHandler.post(updateTimerThread);
}
@Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
@Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
@Override
public void onDestroy() {
Log.v(LOG_TAG, "in onDestroy");
if(onlineTimeHandler!=null){
onlineTimeHandler.removeCallbacks(updateTimerThread);
}
if (mHandlerThread != null) {
mHandlerThread.quit();
}
}
public class MyBinder extends Binder {
TimerService getService() {
return TimerService.this;
}
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
secs = (int) (updatedTime / 1000);
mins = secs / 60;
Intent intent = new Intent();
intent.setAction("android.intent.action.TICK");
sendBroadcast(intent);
if (secs % 60 == 0) {
intent.putExtra("minutes", mins);
sendBroadcast(intent);
}
onlineTimeHandler.postDelayed(this, 1000);
}
};
}
I tried having an abstract BaseActivity
class implement ServiceConnection
, but it appears the service still gets stopped while navigating between activities. Could it be because the BaseActivity's onDestroy
method gets called each time I navigate between activities? I would like it to stay bound unless the app is destroyed or if the device disconnects.