清理堆栈并退出应用程序 onBackPressed()堆栈、应用程序、onBackPressed

2023-09-07 03:09:43 作者:她是WiFi可我没密码i

基本上,我的应用程序有一个 loginScreen,一旦登录,您就可以进行许多活动.当我按下主页按钮时,应用程序进入后台,如果用户在一定时间内没有打开它,则用户会话关闭,你返回登录屏幕.现在的问题是,如果我想在会话过期后从 loginScreen 关闭应用程序,我按返回键,它应该关闭,但它没有.它把我带到堆栈中的前一个元素.

basically my app has a loginScreen and once logged u can go through many activities. when i press the home button the app goes in background and if the user doesnt open it within a certain amount of time, the users session closes and u return to the loginScreen. now the problem is that if i want to close the app from the loginScreen once my session has expired i press the back key and it should close but it doesnt. it brings me to the previous element in the stack.

有线的事情是,在所有 onBackPressed() 方法上,当我开始新的意图时,我总是使用 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);在 loginScreen onBackPressed() 我调用 finish()但它不起作用.有谁知道为什么?以及我该如何解决这个问题.

the wired thing is that on all onBackPressed() methods and when ever i started new intents i always use intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); and on the loginScreen onBackPressed() i call finish() but it doesnt work. anyone know why? and how do i solve this problem.

谢谢你的帮助!!!

代码片段在许多活动中:

code snippets in many activities:

@Override
    public void onBackPressed() {
        mpButtonClick.start();
        Intent intent = new Intent(this, MenuPagina.class); 
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(intent); 
        super.onBackPressed(); 
    }

在登录活动中:

@Override
    public void onBackPressed() {
        super.onBackPressed();
        getIntent().setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        LoginActivity.this.finish();
    }

推荐答案

你可以这样做:

使用 android.os.Process.killProcess(android.os.Process.myPid()); 杀死应用程序. kill app by using android.os.Process.killProcess(android.os.Process.myPid()); on back press.

为此,您需要在清单上添加以下权限.

for this you need to add below permission on manifest.

<uses-permission
        android:name="android.permission.KILL_BACKGROUND_PROCESSES" />

2 .使用默认为 false 的静态布尔isKill"变量,并且每次在登录活动 oncreate() 方法中设置为 false.

2 . use static boolean 'isKill' variable with default false and every time set false in login activity oncreate() method.

在登录活动 onBackPress() 方法中设置 isKill 值为 true.

set isKill value true in login activity onBackPress() method.

然后在每个活动的 onResume() 方法中编写下面的代码

And then write below code in every activity onResume() method

if(isKill)
{
    finish();
}