Double-clicking the android button back to exit the application

I previously asked this question, but unfortunately I did not find a better solution to this problem. Now my application contains the first screen as a splash screen, then the next list (main action), and then clicking on each line of the list opens each action and my requirement is that if we press the back button from any of my internal actions (actions that open when we click on the lines of the list), it should go to my main list, and then, if we click again from the list, the application should close. If I double-click the back button from my list, it will correctly leave the application. But my main problem is that if I double-click the "Back" button from any of my internal activities, my application does not close, I need to press three times instead of closing the application from any of my internal actions. Can anybody help me?

My code to exit the application is I added this code to my main listview class.

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(); } } 

my 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" > 
+6
source share
12 answers

Try this way, hope it helps you solve your problem.

Take one doubleBackToExitPressedOnce flag, which is the default (false) in your activity, and when the back button is pressed, the value of the first time value changes to (ture) and again pressing the button for 2 seconds will exit your application if the return button is not pressed again within the value of the second flag of the second value (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); } 
+14
source

Hi, I know my answer is too late, but please visit the following snippet to get a 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
source

Here is the complete working and simple code for this. And also remember to remove the callbacks in the onDestroy method so that it does not cause a memory leak in the application. :)

 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); } } 
+1
source

This is a guaranteed working solution to exit the application 2 times back.

 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); } 
+1
source

Try adding parent activity to new actions in the manifest.
For instance:

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

In addition to Haresh Chhelana ... Just create one basic action and then increase all other actions from it. This code, which Haresh Chhelana wrote, embeds in your BaseActivity. I think he should solve your problem.

0
source

When you redefine your onBackPressed, after the second click you need:

  • complete the application process:

    ActivityManager am = (ActivityManager) getSystemService (Activity.ACTIVITY_SERVICE); am.killBackgroundProcesses (PackageName);

  • complete your first action. Here is an example: fooobar.com/questions/44987 / ...

UPD

The first case:

 @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { ActivityManager manager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> activityes = ((ActivityManager) manager).getRunningAppProcesses(); for (int i = 0; i < activityes.size(); i++){ if (activityes.get(i).processName.equals(getApplicationInfo().packageName)) { android.os.Process.killProcess(activityes.get(i).pid); } } return; } doubleBackToExitPressedOnce = true; new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; myOwnBackPress(); } }, 1000); } private void myOwnBackPress() { if(!isFinishing()) { super.onBackPressed(); } } 

In fact, google does not recommend killing processes.

Second case:

 //for all activity besides HomeActivity. @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { Intent intent = new Intent(getApplicationContext(), HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("EXIT", true); startActivity(intent); return; } doubleBackToExitPressedOnce = true; new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; myOwnBackPress(); } }, 1000); } private void myOwnBackPress() { if(!isFinishing()) { super.onBackPressed(); } } 

In your HomeActivity, do not override onBackPressed and add the following to onCreate:

  @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // initialize a lot of variables if (getIntent().getBooleanExtra("EXIT", false)) { finish(); } // some code.. } 
0
source

Try this way, I hope it helps you!

  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
source

After you need to repeatedly fulfill the behavioral requirements for capturing double-click, you created a library to do just that. DoubleBackPress Android Library provides convenient processing with built-in templates for such situations.

So, for something like going to the double-click button twice, just do:

 // 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); 

And set the new behavior as the default for clickback in your activity.

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

GIF example of similar requirements

0
source

A simple and easy solution with Toast

In 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(); } } 

In 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
source
  1. Define the name of the global variable Counter.

int counter = 0;

  1. Override the onBacPressed () methods in you MainActivity.java

  2. And follow the instructions below

In 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
source

Define the logical variable name doubleBackToExitPressedOnce.

boolean doubleBackToExitPressedOnce = true;

Override the onBackPressed () method in your MainActivity.java file.

And follow the instructions below

 @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
source

Source: https://habr.com/ru/post/977259/


All Articles