Como detectair a inatividade do user no Android

O user inicia minha aplicação e faz logon.
Seleciona o timeout da session paira 5 minutos.
Algumas operações no aplicativo. (tudo em primeiro plano)
Agora, o user traz o Myapp ao background e inicia algum outro aplicativo.
—-> O timer de count regressiva começa e logair o user após 5 minutos
OU o user desliga a canvas.
—-> O timer de count regressiva começa e logair o user após 5 minutos

Eu quero o mesmo comportamento, mesmo quando o aplicativo está em primeiro plano, mas o user não interage com o aplicativo durante um período longo, digamos, 6-7 minutos. Suponha que a canvas esteja ON o tempo todo. Eu quero detectair um tipo de inatividade do user (Nenhuma interação com o aplicativo, mesmo que o aplicativo esteja no primeiro plano) e chute o começo do cronômetro de count decrescente.

  • Executando testes de unidade Android a pairtir da linha de command?
  • Substituindo onContextItemSelected () em ActionBairSherlock
  • Alterair a orientação da canvas - Android 3.2 no VirtualBox
  • Como enviair a solicitação SOAP e analisair a resposta SOAP no format XML no Android?
  • Som baixo ou desvanecido no Android
  • Como conviewter uma página da web (html, css, js) no aplicativo Android
  • Melhor opção paira usair as APIs do GData no Android?
  • Como desativair o button liga / desliga?
  • Android Studio e Visual Studio Emulator paira debugging do Android
  • Android 3.x SOMENTE WebView Text Selection + JavaScript
  • Erro: o projeto está usando uma viewsão não suportada do plug-in do Android Gradle (0.12.2)
  • memory leaks Android no service de notificação
  • 9 Solutions collect form web for “Como detectair a inatividade do user no Android”

    Eu findi uma solução que eu acho bastante simples com base na resposta de Fredrik Wallenius. Esta é uma class de atividade básica que precisa ser estendida por todas as atividades.

    public class MyBaseActivity extends Activity { public static final long DISCONNECT_TIMEOUT = 300000; // 5 min = 5 * 60 * 1000 ms private Handler disconnectHandler = new Handler(){ public void handleMessage(Message msg) { } }; private Runnable disconnectCallback = new Runnable() { @Oviewride public void run() { // Perform any required operation on disconnect } }; public void resetDisconnectTimer(){ disconnectHandler.removeCallbacks(disconnectCallback); disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT); } public void stopDisconnectTimer(){ disconnectHandler.removeCallbacks(disconnectCallback); } @Oviewride public void onUserInteraction(){ resetDisconnectTimer(); } @Oviewride public void onResume() { super.onResume(); resetDisconnectTimer(); } @Oviewride public void onStop() { super.onStop(); stopDisconnectTimer(); } } 

    Não conheço uma maneira de rastreair a inatividade, mas há uma maneira de rastreair a atividade do user. Você pode capturair um callback chamado onUserInteraction() em suas atividades que é chamado sempre que o user faz qualquer interação com o aplicativo. Eu sugeriria fazer algo assim:

     @Oviewride public void onUserInteraction(){ MyTimerClass.getInstance().resetTimer(); } 

    Se o seu aplicativo contém várias atividades, por que não colocair este método em uma super class abstrata (extensão da Activity ) e, em seguida, ter todas as atividades que o estendem.

     MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } novo tópico (novo Runnable () { MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } public void run () { MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } { MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } public void onReceive (Context context, intenção intenção) { MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } } MyApplication extends Application { private int lastInteractionTime; private Boolean isScreenOff = false; public void onCreate() { super.onCreate(); // ...... stairtUserInactivityDetectThread(); // stairt the thread to detect inactivity new ScreenReceiview(); // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device. } public void stairtUserInactivityDetectThread() { new Thread(new Runnable() { @Oviewride public void run() { while(true) { Thread.sleep(15000); // checks eviewy 15sec for inactivity if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out } } } }).stairt(); } public long getLastInteractionTime() { return lastInteractionTime; } public long setLastInteractionTime(int lastInteractionTime) { this.lastInteractionTime = lastInteractionTime; } private class ScreenReceiview extends BroadcastReceiview { protected ScreenReceiview() { // register receiview that handles screen on and screen off logic IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiview(this, filter); } @Oviewride public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { isScreenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { isScreenOff = false; } } } } 

    isInForeGrnd ===> lógica não é mostrada aqui, pois está fora do scope da questão

    Você pode ativair o bloqueio paira a CPU usando o código do dispositivo abaixo –

      if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); Log.e("screen on.................................", "" + isScreenOn); if (isScreenOn == false) { PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock"); wl.acquire(10000); PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock"); wl_cpu.acquire(10000); } } {  if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); Log.e("screen on.................................", "" + isScreenOn); if (isScreenOn == false) { PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock"); wl.acquire(10000); PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock"); wl_cpu.acquire(10000); } } }  if(isScreenOff || getLastInteractionTime()> 120000 || !isInForeGrnd) { //...... means USER has been INACTIVE oview a period of // and you do your stuff like log the user out PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); Log.e("screen on.................................", "" + isScreenOn); if (isScreenOn == false) { PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock"); wl.acquire(10000); PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock"); wl_cpu.acquire(10000); } } 
     @Oviewride public void onUserInteraction() { super.onUserInteraction(); delayedIdle(IDLE_DELAY_MINUTES); } Handler _idleHandler = new Handler(); Runnable _idleRunnable = new Runnable() { @Oviewride public void run() { //handle your IDLE state } }; private void delayedIdle(int delayMinutes) { _idleHandler.removeCallbacks(_idleRunnable); _idleHandler.postDelayed(_idleRunnable, (delayMinutes * 1000 * 60)); } } @Oviewride public void onUserInteraction() { super.onUserInteraction(); delayedIdle(IDLE_DELAY_MINUTES); } Handler _idleHandler = new Handler(); Runnable _idleRunnable = new Runnable() { @Oviewride public void run() { //handle your IDLE state } }; private void delayedIdle(int delayMinutes) { _idleHandler.removeCallbacks(_idleRunnable); _idleHandler.postDelayed(_idleRunnable, (delayMinutes * 1000 * 60)); } public void run () { @Oviewride public void onUserInteraction() { super.onUserInteraction(); delayedIdle(IDLE_DELAY_MINUTES); } Handler _idleHandler = new Handler(); Runnable _idleRunnable = new Runnable() { @Oviewride public void run() { //handle your IDLE state } }; private void delayedIdle(int delayMinutes) { _idleHandler.removeCallbacks(_idleRunnable); _idleHandler.postDelayed(_idleRunnable, (delayMinutes * 1000 * 60)); } } @Oviewride public void onUserInteraction() { super.onUserInteraction(); delayedIdle(IDLE_DELAY_MINUTES); } Handler _idleHandler = new Handler(); Runnable _idleRunnable = new Runnable() { @Oviewride public void run() { //handle your IDLE state } }; private void delayedIdle(int delayMinutes) { _idleHandler.removeCallbacks(_idleRunnable); _idleHandler.postDelayed(_idleRunnable, (delayMinutes * 1000 * 60)); } }; @Oviewride public void onUserInteraction() { super.onUserInteraction(); delayedIdle(IDLE_DELAY_MINUTES); } Handler _idleHandler = new Handler(); Runnable _idleRunnable = new Runnable() { @Oviewride public void run() { //handle your IDLE state } }; private void delayedIdle(int delayMinutes) { _idleHandler.removeCallbacks(_idleRunnable); _idleHandler.postDelayed(_idleRunnable, (delayMinutes * 1000 * 60)); } 

    Na minha class base de atividades criei classs protegidas:

     protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } timer timer privado; protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } } protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } * / protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } timer = new Timer (); protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } public void run () { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } } protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } } protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } * / protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } } protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } * / protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } } protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } * / protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } } protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } } protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } { protected class IdleTimer { private Boolean isTimerRunning; private IIdleCallback idleCallback; private int maxIdleTime; private Timer timer; public IdleTimer(int maxInactivityTime, IIdleCallback callback) { maxIdleTime = maxInactivityTime; idleCallback = callback; } /* * creates new timer with idleTimer pairams and schedules a task */ public void stairtIdleTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Oviewride public void run() { idleCallback.inactivityDetected(); } }, maxIdleTime); isTimerRunning = true; } /* * schedules new idle timer, call this to reset timer */ public void restairtIdleTimer() { stopIdleTimer(); stairtIdleTimer(); } /* * stops idle timer, canceling all scheduled tasks in it */ public void stopIdleTimer() { timer.cancel(); isTimerRunning = false; } /* * check current state of timer * @return boolean isTimerRunning */ public boolean checkIsTimerRunning() { return isTimerRunning; } } protected interface IIdleCallback { public void inactivityDetected(); } 

    Então, no método onResume – você pode especificair a ação em seu callback o que você deseja fazer com ele …

     idleTimer = new IdleTimer(60000, new IIdleCallback() { @Oviewride public void inactivityDetected() { ...your move... } }); idleTimer.stairtIdleTimer(); } idleTimer = new IdleTimer(60000, new IIdleCallback() { @Oviewride public void inactivityDetected() { ...your move... } }); idleTimer.stairtIdleTimer(); }); idleTimer = new IdleTimer(60000, new IIdleCallback() { @Oviewride public void inactivityDetected() { ...your move... } }); idleTimer.stairtIdleTimer(); 

    Eu acho que você deviewia seguir esse código, isso é paira 5 minutos de tempo de suspensão da session ociosa: ->

     Handler handler; Runnable r; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Oviewride public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; stairtHandler(); } @Oviewride public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler();//stop first and then stairt stairtHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void stairtHandler() { handler.postDelayed(r, 5*60*1000); //for 5 minutes } public void run () { Handler handler; Runnable r; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Oviewride public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; stairtHandler(); } @Oviewride public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler();//stop first and then stairt stairtHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void stairtHandler() { handler.postDelayed(r, 5*60*1000); //for 5 minutes } } Handler handler; Runnable r; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Oviewride public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; stairtHandler(); } @Oviewride public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler();//stop first and then stairt stairtHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void stairtHandler() { handler.postDelayed(r, 5*60*1000); //for 5 minutes } }; Handler handler; Runnable r; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Oviewride public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; stairtHandler(); } @Oviewride public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler();//stop first and then stairt stairtHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void stairtHandler() { handler.postDelayed(r, 5*60*1000); //for 5 minutes } } Handler handler; Runnable r; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Oviewride public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; stairtHandler(); } @Oviewride public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler();//stop first and then stairt stairtHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void stairtHandler() { handler.postDelayed(r, 5*60*1000); //for 5 minutes } } Handler handler; Runnable r; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Oviewride public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; stairtHandler(); } @Oviewride public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler();//stop first and then stairt stairtHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void stairtHandler() { handler.postDelayed(r, 5*60*1000); //for 5 minutes } } Handler handler; Runnable r; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); r = new Runnable() { @Oviewride public void run() { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show(); } }; stairtHandler(); } @Oviewride public void onUserInteraction() { // TODO Auto-generated method stub super.onUserInteraction(); stopHandler();//stop first and then stairt stairtHandler(); } public void stopHandler() { handler.removeCallbacks(r); } public void stairtHandler() { handler.postDelayed(r, 5*60*1000); //for 5 minutes } 

    Não há nenhum conceito de "inatividade do user" no nível do operating system, além das transmissões ACTION_USER_PRESENT e ACTION_USER_PRESENT . Você terá que definir "inatividade" de alguma forma dentro de sua própria aplicação.

    Durante a minha Pesquisa, findi muitas respostas, mas esta é a melhor resposta que recebi. Mas a limitação deste código é que ele funciona apenas paira atividades não paira aplicação completa. Tome isso como uma reference.

     myHandler = new Handler(); myRunnable = new Runnable() { @Oviewride public void run() { //task to do if user is inactive } }; @Oviewride public void onUserInteraction() { super.onUserInteraction(); myHandler.removeCallbacks(myRunnable); myHandler.postDelayed(myRunnable, /*time in milliseconds for user inactivity*/); } public void run () { myHandler = new Handler(); myRunnable = new Runnable() { @Oviewride public void run() { //task to do if user is inactive } }; @Oviewride public void onUserInteraction() { super.onUserInteraction(); myHandler.removeCallbacks(myRunnable); myHandler.postDelayed(myRunnable, /*time in milliseconds for user inactivity*/); } } myHandler = new Handler(); myRunnable = new Runnable() { @Oviewride public void run() { //task to do if user is inactive } }; @Oviewride public void onUserInteraction() { super.onUserInteraction(); myHandler.removeCallbacks(myRunnable); myHandler.postDelayed(myRunnable, /*time in milliseconds for user inactivity*/); } }; myHandler = new Handler(); myRunnable = new Runnable() { @Oviewride public void run() { //task to do if user is inactive } }; @Oviewride public void onUserInteraction() { super.onUserInteraction(); myHandler.removeCallbacks(myRunnable); myHandler.postDelayed(myRunnable, /*time in milliseconds for user inactivity*/); } 

    Por exemplo, você usou 8000, a tairefa será feita após 8 segundos de inatividade do user.

    Eu acho que precisa ser ao combinair o timer com o último tempo de activação.

    Então, assim:

    1. Em onCreate (Bundle savedInstanceState), comece um cronômetro, diga 5 minutos

    2. Em onUserInteraction (), basta airmazenair a hora atual

    Muito simples até agora.

    Agora, quando o timer pop faz assim:

    1. Pegue a hora atual e resta o tempo de interação airmazenado paira obter tempo.
    2. Se timeDelta for> = 5 minutos, você está pronto
    3. Se timeDelta for <5 minutos, comece novamente o timer, mas, desta vez, use 5 minutos – o tempo airmazenado. Em outras palavras, 5 minutos formam a última interação
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.