Question

I have an Activity which keeps beeping till the time the user clicks a button. On clicking the button, it displays a message. After displaying the message, instead of the user pressing on the back button to exit, I want my activity to exit to the home screen on its own.

Does the finish() method do this? If yes, how and where should I implement it?

Any kind of help will be appreciated. Thanks

Was it helpful?

Solution

    Intent i= new Intent("package.homescreenactivity");//homescreen of your app.
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(i);
    finish(); 

Go back to home screen by clearing activity stack.

To understand the whole concept i suggest you take a look at this site. http://developer.android.com/guide/components/tasks-and-back-stack.html. The site talks about how activity back stack works.

Update: (August 15th 2014)

Clearing Backstack may not be a good idea. Please have a look at Effective Navigation design guidelines.

Back button is supposed to take you back to the previous activity.

Check

http://developer.android.com/design/patterns/navigation.html

OTHER TIPS

Apply finish() method in all the activity. It will go back to home screen after activity finishes.

Case 1:For Button Click

public void onClick(View v) {
    // Show message here
    moveTaskToBack(true);
    }

case 2:If You want to ask user to go to home

public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            alertbox.setTitle(res.getString("Title"));
            alertbox.setMessage(res.getString("Exit"));
            alertbox.setIcon(R.drawable.logo);
            alertbox.setPositiveButton(res.getString(R.string.Yes),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                            exit();
                        }
                    });

            alertbox.setNeutralButton(res.getString(R.string.No),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });

            alertbox.show();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        moveTaskToBack(true);

    }

Assuming you are showing the message as an alertdialog, call finish() on the button press of the alertdialog.

If you are using Toast() call finish() on button press after Toast() is shown.

you can apply finish() method at Button onClick() and after startActivity() call you can apply finish method as shown below.

startActivity(intent obj);
finish(); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top