由于android不活动,15分钟后自动注销

时间:2012-11-06 05:26:30

标签: android timer countdowntimer

如果因为用户不活动而在15分钟后在android中使用计时器自动注销?

我在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分钟后显示此类错误消息

This type of error message is shown after 15 mins

8 个答案:

答案 0 :(得分:6)

使用CountDownTimer

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

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

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

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

答案 1 :(得分:4)

我同意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();
}   

答案 2 :(得分:2)

首先创建应用程序类。

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
    }

}

之后,将Base活动扩展到另一个活动中

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);
    }
}

答案 3 :(得分:1)

您可以启动服务并在其中启动计时器。每15分钟,检查一个标志,让我们说inactivity标志设置为真。如果是,请从应用程序注销。

每次用户与您的应用互动时,请将inactivity标记设置为false。

答案 4 :(得分:1)

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

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

。 onUserInteracted类启动一个TimerTaskService,它将成为我案例的内部类,如下所示:

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

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

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秒内运行

答案 5 :(得分: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;
  }
 }

}

在“活动”中使用上述代码,如下所示:

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
    }
}

答案 6 :(得分:0)

充分利用Handler,UserInteraction()和Runnable类。

代码:MainActivity.java

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

    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
           // manageBackup(true,false);
            logout();
        }
    };

    startHandler(); //will start the timer. This must be withing onCreate() scope.

//“不活动代码”部分。

       @Override
public void onUserInteraction() {
    super.onUserInteraction();
    stopHandler();  //first stop the timer and then again start it
    startHandler();
}

public void stopHandler() {
    handler.removeCallbacks(runnable);
}
public void startHandler() {
    handler.postDelayed(runnable, 15*60*1000); //for 15 minutes
}

答案 7 :(得分:0)

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

  @Override
public void onUserInteraction() {
    super.onUserInteraction();
    stopHandler();  //first stop the timer and then again start it
    startHandler();
}