Question

I need to close my application while clicking exit button, have tried with many solution from google like Abstract class, finish, kill process, etc, but it never give any solution

` Screen 1 --> Screen2 --> Screen3 --> Screen 1 ---> screen 2 -- > Screen 1 --> need to Close the application

Was it helpful?

Solution

There is no a straight forward way to do this, I did it this way hope this helps you.

Try this it works fine with me

// clear whole activity stack

    Intent intent = new Intent("clearStackActivity");
    intent.setType("text/plain");
    sendBroadcast(intent);

// start your new activity
Intent intent = new Intent(OrderComplete.this,
                    MainActivity.class);
startActivity(intent);

Step : 1

Put these line in onCreate() method of all Activities or if you have any base activity you can put it there , then no need to put in all activities.

private KillReceiver clearActivityStack;
clearActivityStack = new KillReceiver();
        registerReceiver(clearActivityStack, IntentFilter.create("clearStackActivity", "text/plain"));

Step : 2

Put this class in your Base activity

private final class KillReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }

Explanation :

In above code we created our custom broadcast receiver. And we are registering it in base activity i.e in all activity which invokes.

When we wants to finish all activities we just broadcast intent, so all activity which are register this receiver will notify and finish them self.

OTHER TIPS

if you are destroying the previous activites when you move into next activities then the

system.exit(0);

in last activity will close your entire app

otherwise

try this code

startActivity(new Intent (this,Act_finish.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));

Act_finish

public class Act_finish extends Activity
 {

  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    System.exit(0);
  }

}

Do you actually need those new instances of screen 1 and screen 2 ?

I suggest when you want to navigate to screen 1 from screen 2 or screen 3 you startActivity with an intent with flag ACTIVITY_FLAG_CLEAR_TOP

which will remove all activities form your stack and navigate to screen 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top