Skip to content

Instantly share code, notes, and snippets.

@devmike01
Created October 16, 2019 15:20
Show Gist options
  • Save devmike01/9e5347b6a85384d66577287fd69671ba to your computer and use it in GitHub Desktop.
Save devmike01/9e5347b6a85384d66577287fd69671ba to your computer and use it in GitHub Desktop.
A service that handles app timeout
package devmike.leviapps.co.tensorlitepose.device;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by Gbenga Oladipupo on 2019-10-15.
*/
public class TimeOutService extends IntentService {
public static final String TAG ="TimeOutService";
public static final long TIMEOUT_IN_MINUTES =1;
private boolean isCancelled = false;
private static long lastUsed;
public static void start(Context context){
Intent intent = new Intent(context, TimeOutService.class);
context.startService(intent);
}
public TimeOutService() {
super("TimeOutService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
long idle;
touch();
while (!isCancelled()){
Log.d(TAG, "Log USER OUT IMMEDIATELY IN____ ");
idle = System.currentTimeMillis() - lastUsed;
SystemClock.sleep(1000);
long timeOut =TIMEOUT_IN_MINUTES * (1000 *60);
if (idle >= timeOut){
//if (Foregrou)
Log.d(TAG, "Log USER OUT IMMEDIATELY IN "+lastUsed);
//stopSelf();
setCancelled(true);
idle =0;
}
}
}
public static synchronized void touch() {
Log.d(TAG, "Log TOUCHED!! ");
lastUsed = System.currentTimeMillis();
}
public void setCancelled(boolean isCancelled){
this.isCancelled = isCancelled;
}
public boolean isCancelled() {
return isCancelled;
}
@Override
public void onDestroy(){
Log.d(TAG, "TimeOutService#onDestroy() is called");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment