如何检测Android中的用户不活动状态

时间:2010-11-17 20:13:14

标签: android user-inactivity

用户启动我的应用并登录。
选择会话超时为5分钟 在应用程序上执行某些操作。 (全部在前景)
现在用户将Myapp带到后台并启动其他应用程序。
  ---->倒数计时器启动并在5分钟后注销用户
或者用户关闭屏幕   ---->倒计时器启动并在5分钟后注销用户

即使应用程序位于前台,我也想要相同的行为,但用户不会长时间与应用程序交互6到7分钟。假设屏幕始终处于开启状态。我想检测一下用户不活动(即使应用程序位于前台,也没有与应用程序进行交互)并启动我的倒数计时器。

17 个答案:

答案 0 :(得分:96)

根据Fredrik Wallenius的回答,我想出了一个很简单的解决方案。这是一个需要由所有活动扩展的基本活动类。

public class MyBaseActivity extends Activity {

    public static final long DISCONNECT_TIMEOUT = 300000; // 5 min = 5 * 60 * 1000 ms


    private Handler disconnectHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            // todo
            return true;
        }
    });

    private Runnable disconnectCallback = new Runnable() {
        @Override
        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);
    }

    @Override
    public void onUserInteraction(){
        resetDisconnectTimer();
    }

    @Override
    public void onResume() {
        super.onResume();
        resetDisconnectTimer();
    }

    @Override
    public void onStop() {
        super.onStop();
        stopDisconnectTimer();
    }
}

答案 1 :(得分:79)

我不知道跟踪不活动的方法,但有一种方法可以跟踪用户活动。您可以在活动中捕获名为onUserInteraction()的回调,每次用户与应用程序进行任何交互时都会调用该回调。我建议做这样的事情:

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

如果您的应用包含多个活动,为什么不将此方法放在抽象超类中(扩展Activity),然后让所有活动扩展它。

答案 2 :(得分:14)

我认为你应该使用这段代码,这是5分钟的空闲会话超时: - >

Handler handler;
Runnable r;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    handler = new Handler();
    r = new Runnable() {

       @Override
       public void run() {
            // TODO Auto-generated method stub
            Toast.makeText(MainActivity.this, "user is inactive from last 5 minutes",Toast.LENGTH_SHORT).show();
        }
    };
    startHandler();
}
@Override
public void onUserInteraction() {
     // TODO Auto-generated method stub
     super.onUserInteraction();
     stopHandler();//stop first and then start
     startHandler();
}
public void stopHandler() {
    handler.removeCallbacks(r);
}
public void startHandler() {
    handler.postDelayed(r, 5*60*1000); //for 5 minutes 
}

答案 3 :(得分:8)

public class MyApplication extends Application {
      private int lastInteractionTime;
      private Boolean isScreenOff = false; 
      public void onCreate() {
        super.onCreate();
        // ......   
        startUserInactivityDetectThread(); // start the thread to detect inactivity
        new ScreenReceiver();  // creating receive SCREEN_OFF and SCREEN_ON broadcast msgs from the device.
      }

      public void startUserInactivityDetectThread() {
        new Thread(new Runnable() {
          @Override
          public void run() {
            while(true) {
              Thread.sleep(15000); // checks every 15sec for inactivity
              if(isScreenOff || getLastInteractionTime()> 120000 ||  !isInForeGrnd)
                {
                  //...... means USER has been INACTIVE over a period of
                  // and you do your stuff like log the user out 
                }
              }
          }
        }).start();
      }

      public long getLastInteractionTime() {
        return lastInteractionTime;
      }

      public void setLastInteractionTime(int lastInteractionTime) {
        this.lastInteractionTime = lastInteractionTime;
      }

      private class ScreenReceiver extends BroadcastReceiver {

        protected ScreenReceiver() {
           // register receiver that handles screen on and screen off logic
           IntentFilter filter = new IntentFilter();
           filter.addAction(Intent.ACTION_SCREEN_ON);
           filter.addAction(Intent.ACTION_SCREEN_OFF);
           registerReceiver(this, filter);
        }

        @Override
        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 ===>这里没有显示逻辑,因为它超出了问题的范围

您可以使用下面的设备代码将锁定唤醒到cpu -

  if(isScreenOff || getLastInteractionTime()> 120000 ||  !isInForeGrnd)
    {
      //...... means USER has been INACTIVE over 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);
      }
    }

答案 4 :(得分:6)

@Override
public void onUserInteraction() {
    super.onUserInteraction();
    delayedIdle(IDLE_DELAY_MINUTES);
}

Handler _idleHandler = new Handler();
Runnable _idleRunnable = new Runnable() {
    @Override
    public void run() {
        //handle your IDLE state
    }
};

private void delayedIdle(int delayMinutes) {
    _idleHandler.removeCallbacks(_idleRunnable);
    _idleHandler.postDelayed(_idleRunnable, (delayMinutes * 1000 * 60));
}

答案 5 :(得分:4)

除了ACTION_SCREEN_OFFACTION_USER_PRESENT广播之外,在操作系统级别没有“用户不活动”的概念。您必须在自己的应用程序中以某种方式定义“不活动”。

答案 6 :(得分:3)

在我的活动基类中,我创建了受保护的类:

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 params and schedules a task
     */
    public void startIdleTimer()
    {
        timer = new Timer();            
        timer.schedule(new TimerTask() {

            @Override
            public void run() {             
                idleCallback.inactivityDetected();
            }
        }, maxIdleTime);
        isTimerRunning = true;
    }

    /*
     * schedules new idle timer, call this to reset timer
     */
    public void restartIdleTimer()
    {
        stopIdleTimer();
        startIdleTimer();
    }

    /*
     * 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();
}

所以在 onResume 方法中 - 您可以在回调中指定操作,您希望用它做什么...

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

答案 7 :(得分:3)

即使您可以使用@gfrigon@AKh解决方案来管理您的要求。

但这里有计时器和处理程序免费解决方案。我已经有了很好的管理计时器解决方案。但我已经成功实现了Timer和Handler免费解决方案。

首先,如果您使用计时器或处理程序,我会告诉您您需要管理的内容

  • 如果您的应用被用户或优化程序杀死,您的应用将永远无法自动注销,因为您的所有回调都会被销毁。 (管理一些警报管理器或服务?
  • 每个基类都有计时器吗?您正在为调用注销过程创建许多线程(在应用级别管理静态处理程序或计时器?)。
  • 如果用户处于后台,如果用户在您的应用之外进行其他工作,您的处理程序将启动登录活动。 (管理应用前景或背景?)。
  • 如果屏幕自动关闭怎么办? (在广播接收器上关闭屏幕?

最后,我实施了一个

的解决方案
  1. NO Handler或Timer。
  2. 没有报警管理器。
  3. 不管理App LifeCycle。
  4. ACTION_SCREEN_ON / ACTION_SCREEN_OFF广播接收器。
  5. 最简单可靠的解决方案

    我们不会通过计时器观察用户不活动,而是检查用户活动的最后活动时间。因此,当用户下次交互应用时,我会检查上次交互时间。

    以下是BaseActivity.class,您将从每个活动类而不是LoginActivity扩展。您将在此课程的字段TIMEOUT_IN_MILLI中定义退出时间。

    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.Toast;
    
    public class BaseActivity extends AppCompatActivity {
        public static final long TIMEOUT_IN_MILLI = 1000 * 20;
        public static final String PREF_FILE = "App_Pref";
        public static final String KEY_SP_LAST_INTERACTION_TIME = "KEY_SP_LAST_INTERACTION_TIME";
    
        @Override
        public void onUserInteraction() {
            super.onUserInteraction();
            if (isValidLogin())
                getSharedPreference().edit().putLong(KEY_SP_LAST_INTERACTION_TIME, System.currentTimeMillis()).apply();
            else logout();
        }
    
        public SharedPreferences getSharedPreference() {
            return getSharedPreferences(PREF_FILE, MODE_PRIVATE);
        }
    
        public boolean isValidLogin() {
            long last_edit_time = getSharedPreference().getLong(KEY_SP_LAST_INTERACTION_TIME, 0);
            return last_edit_time == 0 || System.currentTimeMillis() - last_edit_time < TIMEOUT_IN_MILLI;
        }
    
        public void logout() {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            Toast.makeText(this, "User logout due to inactivity", Toast.LENGTH_SHORT).show();
            getSharedPreference().edit().remove(KEY_SP_LAST_INTERACTION_TIME).apply(); // make shared preference null.
        }
    }
    

答案 8 :(得分:2)

在我的搜索过程中,我找到了很多答案,但这是我得到的最佳答案。但是这个代码的限制是它只适用于不适用于整个应用程序的活动。以此为参考。

myHandler = new Handler();
myRunnable = new Runnable() {
    @Override
    public void run() {
        //task to do if user is inactive

    }
};
@Override
public void onUserInteraction() {
    super.onUserInteraction();
    myHandler.removeCallbacks(myRunnable);
    myHandler.postDelayed(myRunnable, /*time in milliseconds for user inactivity*/);
}

例如,如果您使用8000,则任务将在用户不活动8秒后完成。

答案 9 :(得分:1)

用户不活动可以使用android中的onUserInteraction()覆盖方法进行检测

  @Override
    public void onUserInteraction() {
        super.onUserInteraction();

    }

这是示例代码,  用户闲置3分钟后退出(HomeActivity-> LoginActivity)

public class HomeActivity extends AppCompatActivity {

    private static String TAG = "HomeActivity";
    private Handler handler;
    private Runnable r;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        handler = new Handler();
        r = new Runnable() {

            @Override
            public void run() {

                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
                Log.d(TAG, "Logged out after 3 minutes on inactivity.");
                finish();

                Toast.makeText(HomeActivity.this, "Logged out after 3 minutes on inactivity.", Toast.LENGTH_SHORT).show();
            }
        };

        startHandler();

    }

    public void stopHandler() {
        handler.removeCallbacks(r);
        Log.d("HandlerRun", "stopHandlerMain");
    }

    public void startHandler() {
        handler.postDelayed(r, 3 * 60 * 1000);
        Log.d("HandlerRun", "startHandlerMain");
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        stopHandler();
        startHandler();
    }

    @Override
    protected void onPause() {

        stopHandler();
        Log.d("onPause", "onPauseActivity change");
        super.onPause();

    }

    @Override
    protected void onResume() {
        super.onResume();
        startHandler();

        Log.d("onResume", "onResume_restartActivity");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopHandler();
        Log.d("onDestroy", "onDestroyActivity change");

    }

}

答案 10 :(得分:0)

我认为需要将计时器与最后一次激活时间结合起来。

所以这样:

  1. 在onCreate(Bundle savedInstanceState)中启动一个计时器,比如5分钟

  2. 在onUserInteraction()中只存储当前时间

  3. 到目前为止非常简单。

    现在,当计时器弹出这样的时候:

    1. 获取当前时间并减去存储的交互时间以获取timeDelta
    2. 如果timeDelta>&gt; = 5分钟,则完成
    3. 如果timeDelta是&lt; 5分钟再次启动计时器,但这次使用5分钟 - 存储时间。换句话说,5分钟形成最后一次互动

答案 11 :(得分:0)

我有类似SO问题的情况,我需要跟踪用户1分钟的不活动状态,然后重定向用户以启动Activity,我还需要清除活动堆栈。

基于@gfrigon答案,我提出了此解决方案。

ActionBar.java

public abstract class ActionBar extends AppCompatActivity {

    public static final long DISCONNECT_TIMEOUT = 60000; // 1 min

    private final MyHandler mDisconnectHandler = new MyHandler(this);

    private Context mContext;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this;
    }



    /*
    |--------------------------------------------------------------------------
    | Detect user inactivity in Android
    |--------------------------------------------------------------------------
    */

    // Static inner class doesn't hold an implicit reference to the outer class

    private static class MyHandler extends Handler {

        // Using a weak reference means you won't prevent garbage collection

        private final WeakReference<ActionBar> myClassWeakReference;

        public MyHandler(ActionBar actionBarInstance) {

            myClassWeakReference = new WeakReference<ActionBar>(actionBarInstance);
        }

        @Override
        public void handleMessage(Message msg) {

            ActionBar actionBar = myClassWeakReference.get();

            if (actionBar != null) {
                // ...do work here...
            }
        }
    }


    private Runnable disconnectCallback = new Runnable() {

        @Override
        public void run() {

            // Perform any required operation on disconnect

            Intent startActivity = new Intent(mContext, StartActivity.class);

            // Clear activity stack

            startActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            startActivity(startActivity);
        }
    };

    public void resetDisconnectTimer() {

        mDisconnectHandler.removeCallbacks(disconnectCallback);
        mDisconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
    }

    public void stopDisconnectTimer() {

        mDisconnectHandler.removeCallbacks(disconnectCallback);
    }

    @Override
    public void onUserInteraction(){

        resetDisconnectTimer();
    }

    @Override
    public void onResume() {

        super.onResume();
        resetDisconnectTimer();
    }

    @Override
    public void onStop() {

        super.onStop();
        stopDisconnectTimer();
    }
}

补充资源

Android: Clear Activity Stack

This Handler class should be static or leaks might occur

答案 12 :(得分:0)

最好的方法是通过在应用程序calss中注册AppLifecycleCallbacks来处理整个应用程序(假设您有多个活动)。您可以在Application类中将registerActivityLifecycleCallbacks()与以下回调一起使用(我建议创建一个AppLifecycleCallbacks类来扩展ActivityLifecycleCallbacks):

public interface ActivityLifecycleCallbacks {
    void onActivityCreated(Activity activity, Bundle savedInstanceState);
    void onActivityStarted(Activity activity);
    void onActivityResumed(Activity activity);
    void onActivityPaused(Activity activity);
    void onActivityStopped(Activity activity);
    void onActivitySaveInstanceState(Activity activity, Bundle outState);
    void onActivityDestroyed(Activity activity);
}

答案 13 :(得分:0)

在KOTLIN中处理用户的交互超时:

     //Declare handler
      private var timeoutHandler: Handler? = null
      private var interactionTimeoutRunnable: Runnable? = null

 override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_aspect_ratio)

       //Initialise handler
      timeoutHandler =  Handler();
      interactionTimeoutRunnable =  Runnable {
         // Handle Timeout stuffs here
          }

      //start countdown
      startHandler()
}

// reset handler on user interaction
override fun onUserInteraction() {
      super.onUserInteraction()
      resetHandler()
}

 //restart countdown
fun reset() {
      timeoutHandler!!.removeCallbacks(interactionTimeoutRunnable);
      timeoutHandler!!.postDelayed(interactionTimeoutRunnable, 10*1000); //for 10 second

}

 // start countdown
fun startHandler() {
    timeoutHandler!!.postDelayed(interactionTimeoutRunnable, 10*1000); //for 10 second
}

答案 14 :(得分:0)

我知道我想添加这个答案为时已晚,但是对于所有未来的新观众来说,我已经阅读了上面的大多数代码并尝试了一下。但是他们都没有为我工作。下面给出的代码完全可以满足新查看者的需求。该代码将起作用:

public class MainActivity extends AppCompatActivity {

        private Timer timer;
        private Toolbar toolbar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
        }

        @Override
        protected void onPause() {
            super.onPause();

            timer = new Timer();
            Log.i("Main", "Invoking logout timer");
            LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
            timer.schedule(logoutTimeTask, 300000); //auto logout in 5 minutes
        }

        @Override
        protected void onResume() {
            super.onResume();
            if (timer != null) {
                timer.cancel();
                Log.i("Main", "cancel timer");
                timer = null;
            }
        }

        private class LogOutTimerTask extends TimerTask {

            @Override
            public void run() {

                //redirect user to login screen
                Intent i = new Intent(MainActivity.this, YourActivity.class); //where 
             you want to load when inactive 
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                finish();
            }
        }
    }

答案 15 :(得分:0)

这是一个完整的解决方案,可以处理几分钟(例如3分钟)后的用户不活动状态。 这样可以解决常见的问题,例如,当应用程序在后台超时时,活动会跳到前台。

首先,我们创建一个BaseActivity,所有其他Activity都可以扩展。

这是BaseActivity代码。

package com.example.timeout;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


import javax.annotation.Nullable;

public class BaseActivity extends AppCompatActivity implements LogoutListener {

    private Boolean isUserTimedOut = false;
    private static Dialog mDialog;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ((TimeOutApp) getApplication()).registerSessionListener(this);
        ((TimeOutApp) getApplication()).startUserSession();

    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();


    }

    @Override
    protected void onResume() {
        super.onResume();

        if (isUserTimedOut) {
            //show TimerOut dialog
            showTimedOutWindow("Time Out!", this);

        } else {

            ((TimeOutApp) getApplication()).onUserInteracted();

        }

    }

    @Override
    public void onSessionLogout() {


        isUserTimedOut = true;

    }


    public void showTimedOutWindow(String message, Context context) {


        if (mDialog != null) {
            mDialog.dismiss();
        }
        mDialog = new Dialog(context);


        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setContentView(R.layout.dialog_window);

        mDialog.setCancelable(false);
        mDialog.setCanceledOnTouchOutside(false);

        TextView mOkButton = (TextView) mDialog.findViewById(R.id.text_ok);
        TextView text_msg = (TextView) mDialog.findViewById(R.id.text_msg);

        if (message != null && (!TextUtils.isEmpty(message)) && (!message.equalsIgnoreCase("null"))) {
            text_msg.setText(message);

        }


        mOkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mDialog != null){

                    mDialog.dismiss();

                    Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);

                    finish();
                }


            }
        });

        if(!((Activity) context).isFinishing())
        {
            //show dialog
            mDialog.show();
        }

    }

}

接下来,我们为“注销监听器”创建一个接口

package com.example.timeout;

public interface LogoutListener {

    void onSessionLogout();

}

最后,我们创建一个扩展“应用程序”的Java类

package com.example.timeout;

import android.app.Application;

import java.util.Timer;
import java.util.TimerTask;

public class TimeOutApp extends Application {

    private LogoutListener listener;
    private Timer timer;
    private static final long INACTIVE_TIMEOUT = 180000; // 3 min


    public void startUserSession () {
        cancelTimer ();

        timer = new Timer ();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                listener.onSessionLogout ();

            }
        }, INACTIVE_TIMEOUT);

    }

    private void cancelTimer () {
        if (timer !=null) timer.cancel();
    }

    public void registerSessionListener(LogoutListener listener){
        this.listener = listener;
    }

    public void onUserInteracted () {
        startUserSession();
    }


}

注意:不要忘记在清单文件中的应用程序标签中添加“ TimeOutApp”类

<application
        android:name=".TimeOutApp">
        </application>

答案 16 :(得分:0)

open class SubActivity : AppCompatActivity() {
    var myRunnable:Runnable
    private var myHandler = Handler()

    init {
        myRunnable = Runnable{
            toast("time out")
            var intent = Intent(this, MainActivity::class.java)
            startActivity(intent)

        }
    }

    fun toast(text: String) {
        runOnUiThread {
            val toast = Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT)
            toast.show()
        }
    }

   override fun onUserInteraction() {
        super.onUserInteraction();
        myHandler.removeCallbacks(myRunnable)
        myHandler.postDelayed(myRunnable, 3000)
    }

    override fun onPause() {
        super.onPause()
        myHandler.removeCallbacks(myRunnable)
    }

    override fun onResume() {
            super.onResume()
            myHandler.postDelayed(myRunnable, 3000)
    }
}

扩展您的活动

YourActivity:SubActivity(){}

在YourActivity上经过3000毫秒后用户不活动时,进入MainActivity

我使用了先前的答案,并将其转换为kotlin。