5

由于用户不活动,如何在android中使用计时器在15分钟后自动注销?

我在我的 loginActivity.java 中使用了下面的代码

public class BackgroundProcessingService extends Service {

        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
         timer = new CountDownTimer(5 *60 * 1000, 1000) {

                public void onTick(long millisUntilFinished) {
                   //Some code
                    //inactivity = true;
                    timer.start();
                    Log.v("Timer::", "Started");
                }

                public void onFinish() {
                   //Logout
                    Intent intent = new Intent(LoginActivity.this,HomePageActivity.class);
                    startActivity(intent);
                    //inactivity = false;
                    timer.cancel();
                    Log.v("Timer::", "Stoped");
                }
             };
            return null;
        }

    }

和登录按钮的点击我称之为服务意图。

Intent intent1 = new Intent(getApplicationContext(),
                        AddEditDeleteActivity.class);
                startService(intent1);

请指教......

此类错误消息会在 15 分钟后显示

此类错误消息会在 15 分钟后显示

4

7 回答 7

10

使用倒计时

CountDownTimer timer = new CountDownTimer(15 *60 * 1000, 1000) {

        public void onTick(long millisUntilFinished) {
           //Some code
        }

        public void onFinish() {
           //Logout
        }
     };

当用户停止任何操作使用timer.start()以及用户执行操作时timer.cancel()

于 2012-11-06T05:32:09.253 回答
5

我同意 Girish 的上述回答。为了您的方便,我正在与您共享代码。

public class LogoutService extends Service {
        public static CountDownTimer timer;
    @Override
    public void onCreate(){
        super.onCreate();
          timer = new CountDownTimer(1 *60 * 1000, 1000) {
                public void onTick(long millisUntilFinished) {
                   //Some code
                    Log.v(Constants.TAG, "Service Started");
                }

                public void onFinish() {
                    Log.v(Constants.TAG, "Call Logout by Service");
                    // Code for Logout
                    stopSelf();
                }
             };
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

在每个活动中添加以下代码。

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

    LogoutService.timer.start();
}

@Override
protected void onStop() {
    super.onStop();
    LogoutService.timer.cancel();
}   
于 2014-03-27T07:45:03.027 回答
4

首先创建应用程序类。

public class App extends Application{

   private static LogoutListener logoutListener = null;
   private static Timer timer = null;

   @Override
   public void onCreate() {
       super.onCreate();
   }


   public static void userSessionStart() {
           if (timer != null) {
               timer.cancel();
           }
           timer = new Timer();
           timer.schedule(new TimerTask() {
               @Override
               public void run() {
                   if (logoutListener != null) {
                       logoutListener.onSessionLogout();
                       log.d("App", "Session Destroyed");
                   }
               }
           },  (1000 * 60 * 2) );
       }

       public static void resetSession() {
           userSessionStart();
       }

       public static void registerSessionListener(LogoutListener listener) {
           logoutListener = listener;
       }
}

此应用程序类添加到清单中

<application
       android:name=".App"
       android:allowBackup="false"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:roundIcon="@mipmap/ic_launcher_round"
       android:supportsRtl="true"
       android:usesCleartextTraffic="true"
       android:theme="@style/AppTheme">
       <activity android:name=".view.activity.MainActivity"/>

</application>

然后创建在整个应用程序中使用的 BaseActivity 类

class BaseActivity extends AppCompatActivity implements LogoutListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //setTheme(App.getApplicationTheme());
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Set Listener to receive events
        App.registerSessionListener(this);
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        //reset session when user interact
        App.resetSession();

    }

    @Override
    public void onSessionLogout() {
        // Do You Task on session out
    }

}

之后在另一个活动中扩展基本活动

public class MainActivity extends BaseActivity{

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
于 2020-05-04T09:40:01.947 回答
1

您可以启动服务并在其中启动计时器。每 15 分钟检查一次标志,假设inactivity标志设置为真。如果是,请退出应用程序。

每次用户与您的应用交互时,将inactivity标志设置为 false。

于 2012-11-06T05:33:39.033 回答
1

您可能需要创建一个 BaseActivity 类,您的应用程序中的所有其他活动都将扩展该类。在该类中,在 onUserInteraction 方法中启动您的计时器任务 (TimerTask()):

override fun onUserInteraction() {
    super.onUserInteraction()
    onUserInteracted()
}

. onUserInteracted 类启动一个 TimerTaskService ,这将是我的内部类,如下所示:

private fun onUserInteracted() {
     timer?.schedule(TimerTaskService(), 10000)
}

TimerTaskService 类将如下所示。请注意在 UI 线程上运行,以防您希望在登录用户之前显示 DialogFragment 以完成要执行的操作:

inner class TimerTaskService : TimerTask() {
    override fun run() {
        /**This will only run when application is in background
         * it allows the application process to get high priority for the user to take action
         * on the application auto Logout
         * */
//            val activityManager = applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
//            activityManager.moveTaskToFront(taskId, ActivityManager.MOVE_TASK_NO_USER_ACTION)

        runOnUiThread {
            displayFragment(AutoLogoutDialogFragment())
            isSessionExpired = true
        }
        stopLoginTimer()
    }
}

你会意识到我有一个 stopTimer 方法,你必须在预期的动作被调用后调用,这个类只是有timer?.cancel(),你可能还需要将它包含在onStop()方法中。

注意:由于 10000 毫秒,这将在 10 秒内运行

于 2018-03-22T15:37:15.320 回答
0

我希望这个能帮上忙

我在github上找到了它https://gist.github.com/dseerapu/b768728b3b4ccf282c7806a3745d0347

public class LogOutTimerUtil {

 public interface LogOutListener {
  void doLogout();
 }

 static Timer longTimer;
 static final int LOGOUT_TIME = 600000; // delay in milliseconds i.e. 5 min = 300000 ms or use timeout argument

 public static synchronized void startLogoutTimer(final Context context, final LogOutListener logOutListener) {
  if (longTimer != null) {
   longTimer.cancel();
   longTimer = null;
  }
  if (longTimer == null) {

   longTimer = new Timer();

   longTimer.schedule(new TimerTask() {

    public void run() {

     cancel();

     longTimer = null;

     try {
      boolean foreGround = new ForegroundCheckTask().execute(context).get();

      if (foreGround) {
       logOutListener.doLogout();
      }

     } catch (InterruptedException e) {
      e.printStackTrace();
     } catch (ExecutionException e) {
      e.printStackTrace();
     }

    }
   }, LOGOUT_TIME);
  }
 }

 public static synchronized void stopLogoutTimer() {
  if (longTimer != null) {
   longTimer.cancel();
   longTimer = null;
  }
 }

 static class ForegroundCheckTask extends AsyncTask < Context, Void, Boolean > {

  @Override
  protected Boolean doInBackground(Context...params) {
   final Context context = params[0].getApplicationContext();
   return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
   ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   List < ActivityManager.RunningAppProcessInfo > appProcesses = activityManager.getRunningAppProcesses();
   if (appProcesses == null) {
    return false;
   }
   final String packageName = context.getPackageName();
   for (ActivityManager.RunningAppProcessInfo appProcess: appProcesses) {
    if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
     return true;
    }
   }
   return false;
  }
 }

}

在 Activity 中使用上面的代码,如下所示:

public class MainActivity extends AppCompatActivity implements LogOutTimerUtil.LogOutListener
{
    @Override
    protected void onStart() {
        super.onStart();
        LogOutTimerUtil.startLogoutTimer(this, this);
        Log.e(TAG, "OnStart () &&& Starting timer");
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        LogOutTimerUtil.startLogoutTimer(this, this);
        Log.e(TAG, "User interacting with screen");
    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause()");
    }

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

        Log.e(TAG, "onResume()");
    }

    /**
     * Performing idle time logout
     */
    @Override
    public void doLogout() {
      // write your stuff here
    }
}
于 2018-07-13T12:41:24.533 回答
0

使用名为:的内置函数,onUserInteraction()如下所示:

  @Override
public void onUserInteraction() {
    super.onUserInteraction();
    stopHandler();  //first stop the timer and then again start it
    startHandler();
}
于 2020-05-28T07:15:14.973 回答