Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

java - Exit the app when back button in device is clicked

There are 3 activities in my app.

Activity A(Main Page) -> Activity B -> Activity C.

When submit button in Activity C is clicked, it will back to Activity A again. When I click the back button in device to exit the app, it will back to Activity C again, then B and A , then only can exit.

Is there a way to let the app straight away exit when back button in device is pressed in Activity A?

I add below code in Activity A, but the problem is it still goes to Activity C instead of exit.

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;                       
        }
    }, 2000);
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Probably when you submit on activity C instead of closing it, you're opening activity A again. So do the following: start activity C for result from activity B, when you submit on activity C call setResult() and then call finish() on activity C then override onActivityResult() in activity B and when you get the result from activity C call finish () on activity B. Then you're back to activity A and if you press back, your APP will close. :) Hope this helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...