The best solution to make a timer run on background is doing it through a Service
.
Create a Service
, which you start (and pass to it the instance of your timer) on the onPause
method and you destroy it(and retrieve the timer) on the onResume
method when you brin your main activity on top.
EDIT:
public class TimerService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("SERVICE", "CREATED");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("SERVICE", "DESTROYED");
//Save your timer instance on destroy service
}
@Override
public void onLowMemory() {
super.onLowMemory();
Log.i("SERVICE", "LOW MEMORY");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Retrieve the timer instance here and use it...
//Restart service if Android destroys it!
return Service.START_NOT_STICKY;
}
}
In your main activity, in onPause
start the service (onPause
is called when activity goes in background):
Intent inetnt=new Intent(this, TimerService.class);
intnet.putExtra("Timer", YourTimerInstance); //Instance as string or int...
startService(inetnt);
In your main activity, in onResume
(called when your activity comes in foreground again) stop the service and retrieve the instance from it. To do this you can use SharedPreferences
(there are thounsands examples of SharedPreferences
in google). To start the service:
Intent inetnt=new Intent(this, TimerService.class);
//Retrieve timer instance
stopService(inetnt);
Hope it helps!