Check if user has browsed out from android application

121 views Asked by At

Code for checking if user is browsed out from application:

public boolean isApplicationSentToBackground(final Context context) {
    try {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(
                    context.getPackageName())) {
                return true;
            }
        }
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

protected void onPause() {
    Log.i("Status", "onPause");
    super.onPause();

    SharedPreferences prefs =
        PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean security = prefs.getBoolean("prefSecurity", false);

    try{
        if(isApplicationSentToBackground(getApplicationContext()) == false){
            if(security == true)  {
                SharedPreferences settings = getSharedPreferences(PREFS_NAME,
                    MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("prefSecurityCheck", "putsis");
                editor.commit();
        }
      }
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "Something Went Wrong!",
            Toast.LENGTH_SHORT).show();
    }
}

I have made that user can have an option to enter a security code before he can see the app. And it checks from sharedpreferences if we need to ask the security code, if it saves "putsis" then the next time we open mainactivity it asks for security code, and when right code is entered then it changes prefSecurityCheck to "korras" and no code check is made.

Right now two problems are that:

When I go to app settings or press share button it counts like I've went out of the app.

If i press recent button or sometimes home button and reopen it, it won't always show security screen, I think it is due to the fact that it doesn't save those preferences fast enough to sharedpreferences.

0

There are 0 answers