2

in the MainActivity , I have this code for closing the application :

@Override
public void onBackPressed() {
    if (exit){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();

        super.onBackPressed();
    }else {
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }

I should press 2 back button when I want to close the application .

The problem is ,when I close the application, it starts from another activity , mostly from the last activity I've been to .

How can I always start the activity from mainActivity not other activities ?

mohamad bagheri
  • 499
  • 1
  • 10
  • 25

5 Answers5

2

Use these lines of code..

    @Override
 public void onBackPressed() {
     super.onBackPressed();
  if (exit){
  Intent intent = new Intent(Intent.ACTION_MAIN);
         intent.addCategory(Intent.CATEGORY_HOME);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
         intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
        finish();
      }else {
         exit = true;
         new Handler().postDelayed(new Runnable() {
          @Override
           public void run() {
              exit = false;
          }
       }, 3 * 1000);
   }
}
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
1

you have to kill all the activities when you are closing your application, have a look at this How to kill an application with all its activities?

Community
  • 1
  • 1
Zubair Akber
  • 2,760
  • 13
  • 30
1

override the onBackPressed method of your MainActivity as shown below

private int backpressedCount;
@Override
public void onBackPressed() {
    backpressedCount++;
    if (backpressedCount == 2) {
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
nvinayshetty
  • 3,187
  • 1
  • 21
  • 32
1

Write this part of code in every / in which activity is starting automatically,

@Override
public void onBackPressed() {
YourActivityName.this.finish();
}
Exigente05
  • 2,161
  • 3
  • 22
  • 42
1

try the launchMode: singleTask or singleInstance

<activity
    android:name=".MainActivity"
    android:launchMode="singleInstance">
islq
  • 86
  • 10