点击两次安卓返回按钮退出应用程序

7
我的应用程序包含一个初始的启动画面,后面是一个列表视图(主活动)。单击listview中的每一行将打开每个活动。
我的要求是,如果我们从任何内部活动(单击listview行时打开的活动)单击返回按钮,则必须导航到我的主listview,然后再次从listview单击一次以关闭应用程序。
因此,如果我两次从我的listview按下返回按钮,它将正确退出应用程序。我的主要问题是,如果我从任何内部活动两次按下返回按钮,我的应用程序不会关闭。我需要按三次,而不是从任何内部活动关闭应用程序。请问有人可以帮助我吗?
这是退出应用程序的代码。 我在我的主listview类中添加了这段代码。
private static final int TIME_INTERVAL = 3000; // # milliseconds, desired time passed between two back presses.
private long mBackPressed;

@Override
public void onBackPressed()
{
    if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) 
    { 
        super.onBackPressed(); 
        return;
    }
    else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }

    mBackPressed = System.currentTimeMillis();
}
} 

我的manifest.xml

<application
    android:allowBackup="true"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"> 

    <meta-data android:name="com.google.android.gms.version"
       android:value="@integer/google_play_services_version"/>


    <activity
        android:name="learnersseries.mathematics.complexnumbers.Firstintro"
         android:screenOrientation="portrait" 
         android:launchMode="singleTop"            
        android:label="@string/app_name" >


        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />

        </intent-filter>
    </activity>


    <activity android:name="Myintegralpage"
        android:screenOrientation="portrait"
                   >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="myimagine"
        android:screenOrientation="portrait" 

       >
        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Myintroductionpage"
        android:screenOrientation="portrait" 

      >
        <intent-filter></intent-filter>
    </activity>
    <activity android:name="MainActivity"
        android:noHistory="false"
        android:screenOrientation="portrait" 
       >


        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Complexnumbers"
        android:screenOrientation="portrait"
         >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Equality"
        android:screenOrientation="portrait"
         >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Additionofcomplex"
        android:screenOrientation="portrait"
          >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Subtraction"
        android:screenOrientation="portrait" 
        >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="multiplication"
        android:screenOrientation="portrait" >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Division"
        android:screenOrientation="portrait" >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Conjugate"
        android:screenOrientation="portrait" >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Modulus"
        android:screenOrientation="portrait" >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Reciprocal"
        android:screenOrientation="portrait" >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Square"
        android:screenOrientation="portrait">


    </activity>
    <activity android:name="Representation"
        android:screenOrientation="portrait" >

        <intent-filter></intent-filter>
    </activity>
    <activity android:name="Argument"
        android:screenOrientation="portrait" >
13个回答

13

尝试这种方法,希望它能帮助你解决问题。

在你的Activity中,定义一个名为doubleBackToExitPressedOnce的标志,默认情况下为false。当按下返回按钮时,将标志值第一次更改为true,如果在2秒内再次按下返回按钮,则退出应用程序,如果再次按下返回按钮超过2秒,则将标志值设置为false。

private boolean backPressedToExitOnce;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;                       
        }
    }, 2000);
} 

谢谢。但是它没有起作用,我得按三次返回按钮才能退出我的活动,结果还是一样的。 - Thushara prasad
@Thusharaprasad,你需要按三次返回按钮才能退出吗? - Haresh Chhelana
当我从任何一个活动中按两次时,它必须退出。如果我从我的ListView中按两次,它必须退出,如果我从任何一个活动中按两次,它也必须退出。现在的问题是,如果我从我的内部活动中按两次,它会显示Toast消息“再按一次退出”。 - Thushara prasad
那么如果您不需要显示这个提示,只需删除Toast代码即可。 - Haresh Chhelana
这段代码仅适用于ListView(主活动),不能在所有其他活动(即当我们按下ListView项目时打开的活动)中使用。 - Thushara prasad

3

这是一个保证可行的解决方案,可以通过2次后退按钮按下退出应用程序

int doubleBackToExitPressed = 1;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onBackPressed() {
    if (doubleBackToExitPressed == 2) {
        finishAffinity();
        System.exit(0);
    }
    else {
        doubleBackToExitPressed++;
        Toast.makeText(this, "Please press Back again to exit", Toast.LENGTH_SHORT).show();
    }

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressed=1;`enter code here`
        }
    }, 2000);
}

2

Hi I know that my answer is too late but Please take tour on the following snippet to get clear solution:

@Override
public void onBackPressed() {
    if(canExit)
        super.onBackPressed();
    else{
        canExit = true;
        Toast.makeText(getApplicationContext(), "Press again", Toast.LENGTH_SHORT).show();
    }
    mHandler.sendEmptyMessageDelayed(1, 2000/*time interval to next press in milli second*/);// if not pressed within 2seconds then will be setted(canExit) as false
}


public Handler mHandler = new Handler(){

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
            case 1:
                canExit = false;
                break;
            default:
                break;
            }
        }
    };


1
这里是完整的、简单的代码来实现此功能。同时不要忘记在onDestroy方法中移除回调,以免在应用程序中引起内存泄漏。 :)
private boolean backPressedOnce = false;
private Handler statusUpdateHandler = new Handler();
private Runnable statusUpdateRunnable;

public void onBackPressed() {
        if (backPressedOnce) {
            finish();
        }

        backPressedOnce = true;
        final Toast toast = Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT);
        toast.show();

        statusUpdateRunnable = new Runnable() {
            @Override
            public void run() {
                backPressedOnce = false;
                toast.cancel();  //Removes the toast after the exit.
            }
        };

        statusUpdateHandler.postDelayed(statusUpdateRunnable, 2000);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (statusUpdateHandler != null) {
        statusUpdateHandler.removeCallbacks(statusUpdateRunnable);
    }
}

您忘记初始化statusUpdateHandler。 - AbhinayMe

0

在编程中,经常需要实现双击返回键的行为需求。因此,我建立了一个库来处理这个问题。DoubleBackPress Android Library 提供了内置模板,方便处理这种情况。

例如,如果要在按两次返回键时退出应用程序,只需执行以下操作:

// set the Action to occur on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
    @Override
    public void actionCall() {
          // TODO : Exiting application code
          finish();
    }
};

// setup DoubleBackPress behaviour
DoubleBackPress doubleBackPress = new DoubleBackPress()
        .withDoublePressDuration(3000)                  // timeout duration - msec
        .withDoubleBackPressAction(doubleBackPressAction);

并将新行为设置为您的 Activity 中返回按键的默认行为。

@Override
public void onBackPressed() {
    doubleBackPress.onBackPressed();
}

类似需求的示例GIF


0
尝试这种方法,希望能对你有所帮助!
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        switch (event.getAction()) {
        case KeyEvent.ACTION_DOWN:
            if (event.getDownTime() - lastPressedTime < PERIOD) {
                moveTaskToBack(true);
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Press again to exit.", Toast.LENGTH_SHORT).show();
                lastPressedTime = event.getEventTime();
            }
            return true;
        }
    }
    return false;
}

0

使用Toast的简单易行的解决方案

在Java中

private Toast exitToast;

@Override
public void onBackPressed() {
    if (exitToast == null || exitToast.getView() == null || exitToast.getView().getWindowToken() == null) {
        exitToast = Toast.makeText(this, "Press again to exit", Toast.LENGTH_LONG);
        exitToast.show();
    } else {
        exitToast.cancel();
        super.onBackPressed();
    }
}

在 Kotlin 中
private var exitToast: Toast? = null

override fun onBackPressed() {
    if (exitToast == null || exitToast!!.view == null || exitToast!!.view.windowToken == null) {
        exitToast = Toast.makeText(this, "Press again to exit", Toast.LENGTH_LONG)
        exitToast!!.show()
    } else {
        exitToast!!.cancel()
        super.onBackPressed()
    }
}

0
  1. 定义一个全局变量名为Counter。

int counter=0;

  1. 在你的MainActivity.java中重写onBackPressed()方法

  2. 并按照以下步骤进行操作:

在Java中

    @Override
    public void onBackPressed() {
        counter+=1;
        if (counter==2){
            super.onBackPressed();
        }else {
            Toast.makeText(this, "Press one more time to exit", Toast.LENGTH_SHORT).show();
        }

    }

0

定义一个布尔变量名为doubleBackToExitPressedOnce。

boolean doubleBackToExitPressedOnce = true;

在MainActivity.java中重写onBackPressed()方法

并按照以下步骤进行操作:

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        if (doubleBackToExitPressedOnce) {
            this.doubleBackToExitPressedOnce = false;
            Globals.showToast(this, "Please press back again to exit.");
        } else {
            finish();
        }
    }
}

0

尝试在清单中的新活动中添加父活动。
例如:

<activity android:name="myimagine"
          android:screenOrientation="portrait"
          android:parentActivityName="com.example.previous_activity" />

感谢您的回复。但很抱歉,这个程序需要最低API级别为16,而我正在测试一个API级别为14的设备上。 - Thushara prasad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接