Может быть, это поможет вам
В соответствии с Google новый механизм LifecycleObserver
поможет вам
Во-первых, добавьте это ниже зависимость от буксировки В Project ваше приложение
Во-первых, добавьте в project-level gradle
allprojects {
repositories {
google()
jcenter()
maven { url 'https://maven.google.com' }
}
}
Затем после на уровне приложения gradle
implementation "android.arch.lifecycle:extensions:1.1.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
Затем после создания класса приложения и добавления нижеприведенной логики (Примечание: если вы уже создали, изменитеи добавьте ниже несколько методов)
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
}
}
}
И, наконец, если вы не зарегистрировали этот класс в манифесте, зарегистрируйтесь, чтобы установить тег имени в вашем манифесте
<application
android:name=".MyApplication"