简体   繁体   中英

How to Logout the API when Application cleared from stack i.e when app goes to destroy state in android

I'm devloping banking application, i want to do autologout the application after 5 minutes when user is inactivity state and destroy the application.

I'm using timer for foreground service after 5 mintues it will come to login screen.

Without clicking logout option user is clear the application that means destroying the application.how autologout will work. Give me solution.

This code im calling in "onuserinteracted method in common activity"

public class MyApp1 extends Application {
    private LogOutListener1 listener;
    private Timer timer;
    private Context context;


    public void startUserSession(Context ctx) {
        this.context = ctx;
        long sessiontime = Prefs.getsessiontime(ctx);
        final long milliseconds = sessiontime * 60000;
        cancelTimer();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    boolean foreGround = new ForegroundCheckTask().execute(context).get();
                    if (foreGround) {
                        listener.onSessionLogout();
                    } else {
                        long millis = new Date().getTime();
                        Prefs.setcurrenttimestamp(context, millis);
                    }


                } catch (InterruptedException | ExecutionException ignored) {

                }
            }

        }, milliseconds);
    }

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

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

    public void onUserInteracted() {
        startUserSession(context);
    }

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

}

Maybe this helps you

As per google new LifecycleObserver mechanism will help you

First, add this below tow dependancy In Project your app
First, add in project-level gradle

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

Then after in App-level gradle

implementation "android.arch.lifecycle:extensions:1.1.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"

Then after creating your application class and add bellow logic (Note: if you already created then modify and add below some methods)

public class MyApplication extends Application implements LifecycleObserver {


    String strPrafKey = "bi_vrnfX";
    String strKeyTime = "timeKey";
    private String strKeyLogin = "is_login";

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppBackgrounded() {
        //App in background

        //Store app goes in background time
        SharedPreferences sharedpreferences = getSharedPreferences(strPrafKey, Context.MODE_PRIVATE);
        long currentTimeInSecond = Calendar.getInstance().getTimeInMillis() / 1000;
        sharedpreferences.edit().putLong(strKeyTime, currentTimeInSecond).apply();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        // App in foreground

        SharedPreferences sharedpreferences = getSharedPreferences(strPrafKey, Context.MODE_PRIVATE);
        long lastBackgroundTime = sharedpreferences.getLong(strKeyTime, 0); //Take last background time for compare
        long currentTimeInSecond = Calendar.getInstance().getTimeInMillis() / 1000;
        long timeDeffrance = (currentTimeInSecond - lastBackgroundTime) / 60; //Diffrance of last background and current time in minute
        if (timeDeffrance > 5) {
            sharedpreferences.edit().putBoolean(strKeyLogin, false).apply();
            //You can replace this code or data with which you are comparing in your login
        }
    }
}

And finally, if you have not registered this class in manifest then register to set name tag in your manifest

<application
        android:name=".MyApplication"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM