1

I have an application in which I have different activities. In 1 activity, I want that when the user presses the back button, I want the application to be closed and home screen is displayed

Code

public boolean onKeyDown(int keyCode, KeyEvent event) 
        {
            //Handle the back button
            if(keyCode == KeyEvent.KEYCODE_BACK) 
                {
                    //Ask the user if they want to quit
                    new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Exit")
                    .setMessage("Really Exit ?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
                        {
                            public void onClick(DialogInterface dialog, int which) 
                                {
                                 Intent intent = new Intent(Intent.ACTION_MAIN);
                                intent.addCategory(Intent.CATEGORY_HOME);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                }
                        })
                    .setNegativeButton("No", null)
                    .show();
                    return true;
                }
            else 
                {
                return super.onKeyDown(keyCode, event);
                }
        }

When I run this and press the back button, the home screen is displayed, but when I run it for the second time, I get a console output as

ActivityManager: Warning: Activity not started, its current task has been brought to the front.

And the activity in which the back button is pressed gets displayed. I think the application does not get killed and runs in background. Just to mention, this is not the starting activity of my application.

Can somebody help me, I am beginner.

gideon
  • 19,329
  • 11
  • 72
  • 113
kumar piyush
  • 173
  • 2
  • 6
  • 15
  • Your question is not clear dear. – Harneet Kaur Jun 18 '12 at 04:48
  • write `finish();` in onPause()... – GAMA Jun 18 '12 at 04:52
  • Point of Information: Since Android 2.0 the default top-level handler for the back button has been in the default (Activity class) implementation of onKeyUp(), not onKeyDown(). So if you're going to attempt to modify this behavior (e.g., by prompting for confirmation), the place to do that would probably be in an override of onKeyUp(). This default Activity.onKeyUp() itself calls onBackPressed(), and its default implementation is to call finish(), which ends your current (main) activity. – Carl Nov 07 '12 at 00:31
  • So, if you're intercepting the back button and putting up a dialog instead, then you'll have to call finish() yourself in the onClick() handler for the Yes button in that dialog. – Carl Nov 07 '12 at 00:31

7 Answers7

4

Try this code :

@Override
public void onBackPressed()
{
      moveTaskToBack(true);
}

Also check this Link

Community
  • 1
  • 1
Krishna Suthar
  • 3,071
  • 6
  • 31
  • 37
3

For each and every Intent you have used for going into other activity u have to follow this way for passing intent just pass flag to each intent as given below and after starting Activity using startActivity() u have to add finish() after that demo code as given below

Intent i=new Intent(firstActivity.this,secondActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
Khan
  • 7,585
  • 3
  • 27
  • 44
2

You cannot kill your application at your will. The android OS will do it when it wishes to free the resources allocated to it. You cannot actually implement the exit application concept in android. The user can simply navigate away from your Activity and return to it. If it has to be restarted from the first Activity or resumed where it left, is upto the android OS, not you.

Read this post to understand the philosophy of how android apps should be designed and why you wouldn't want to exit at your will: Is quitting an application frowned upon?

Community
  • 1
  • 1
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
  • So , when i navigate away from my app to the home screen and then I re-run my app. the last run activity will be displayed and not the starting activity .. Isn't there anyway I can achieve the deesired output.? – kumar piyush Jun 18 '12 at 04:52
  • You can call `finish()` on that `Activity` to tell the OS that your are done with that `Activity` and the OS is free to destroy and deallocate the resources alloted to it. – Kazekage Gaara Jun 18 '12 at 04:53
  • 2
    And as for your desperate attempt to exit your Application, then you must call `finish()` on every `Activity` once your navigate away from it. – Kazekage Gaara Jun 18 '12 at 04:55
  • 1
    Your application is made up of several `Activities`. You will have to call `finish()` on all. – Kazekage Gaara Jun 18 '12 at 04:57
  • 1
    @kumarpiyush read [this post](http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2034238#2034238) to understand better Android application model. You'll understand **why** you shouldn't exit yourself. – gideon Jun 18 '12 at 05:04
  • @gideon you might want to edit my answer and add this link as well to it. – Kazekage Gaara Jun 18 '12 at 05:05
1

Add finish(); after that line startActivity(intent) it finish your activity.

Thanks

Praveenkumar
  • 24,084
  • 23
  • 95
  • 173
Md Abdul Gafur
  • 6,213
  • 2
  • 27
  • 37
1

you need to include this class as such in your code.........

  public abstract class AppBaseActivity extends Activity {
public static final String FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION =    "com.hrupin.FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION";
private BaseActivityReceiver baseActivityReceiver = new BaseActivityReceiver();
public static final IntentFilter INTENT_FILTER = createIntentFilter();

private static IntentFilter createIntentFilter(){
    IntentFilter filter = new IntentFilter();
    filter.addAction(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION);
    return filter;
}

protected void registerBaseActivityReceiver() {
    registerReceiver(baseActivityReceiver, INTENT_FILTER);
}

protected void unRegisterBaseActivityReceiver() {
    unregisterReceiver(baseActivityReceiver);
}

public class BaseActivityReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION)){
            finish();
        }
    }
} 

protected void closeAllActivities(){
    sendBroadcast(new Intent(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION));
}
  }

Then you need to extend all other classes from this class just as in an example below:

    public class FirstActivity extends AppBaseActivity implements OnClickListener {
/** Called when the activity is first created. */

private Button buttonOpenNextActivity;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first);
    registerBaseActivityReceiver();
    buttonOpenNextActivity = (Button)findViewById(R.id.buttonOpenNextActivity);
    buttonOpenNextActivity.setOnClickListener(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unRegisterBaseActivityReceiver();
}

@Override
public void onClick(View v) {
    /* OPEN SECOND ACTIVITY.*/
    startActivity(new Intent(this, SecondActivity.class));
}
  }

Another class:

       public class SecondActivity extends AppBaseActivity implements OnClickListener {
private Button buttonOpenNextActivity;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
    registerBaseActivityReceiver();
    buttonOpenNextActivity = (Button)findViewById(R.id.buttonOpenNextActivity);
    buttonOpenNextActivity.setOnClickListener(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unRegisterBaseActivityReceiver();
}

@Override
public void onClick(View v) {
    /* OPEN THIRD ACTIVITY.*/
    startActivity(new Intent(this, ThirdActivity.class));
}
            }

Last Class:

      public class ThirdActivity extends AppBaseActivity  implements OnClickListener  {
private Button buttonCloseAllActivities;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.third);
    registerBaseActivityReceiver();
    buttonCloseAllActivities = (Button)findViewById(R.id.buttonCloseAllActivities);
    buttonCloseAllActivities.setOnClickListener(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unRegisterBaseActivityReceiver();
}

 @Override
protected void onBackPressed() {
    closeAllActivities();
    super.onBackPressed();
}
}

Now when you press back button in third activity all other activities will also be finished altogether.

1/ dont forget to register the reciever in onCreate and unregister() it in ondestroy().

Anu
  • 552
  • 3
  • 9
0

Your question is not clear dear.

As per my knowledge you should use broadCast Reciever for finishing the application and passing the intent to home Screen.

MoreOver Warning is nothing , before running your application just press Enter in your code or give sm space and den save it and re- run you appication.It will work fine....

Harneet Kaur
  • 4,487
  • 1
  • 16
  • 16
0

if you want to exit your application on back press then you have to finish all the previous activities when you press the back button on that screen for this you should use the concept of BROADCAST RECIEVER ...... means you have broadcast an intent on that back press which will finish all the previous activities.

Anu
  • 552
  • 3
  • 9