简体   繁体   中英

Android finish() StartActivityForResult not working

I have a problem in Android with the finish() function:

I am trying to obtain the following behavior: when the user lunches the application for the first time, I want to start a wizard procedure. I am using a PageViewer with different fragmets. I want that the application closes, if the user presses the back button while it is in the first page.

Here what I did:

In the main activity I check if the user has started the application for the first time. If this is the case, then I start a new activity (the wizard)

if(firstTime) {
    // here activity is the main activity
    Intent i = new Intent(activity, Wizard.class);
    activity.startActivityForResult(i,0);
}

In the wizard activity class I override the onBackPressed method:

@Override
public void onBackPressed(){
    if(pager.getCurrentItem() == 0) {
        setResult(5);
        finish();
    } else{
        // code
    }
}

When finish() is called, Android invokes the onActivityResult method of the parent activity (the main activity):

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(resultCode == 5) {
        finish()
    } 
}

What I expect is the application to be closed. What I get is that Android calls onResume and, then, onCreate methods, starting the wizard from the beginning. Then, if from this new wizard I press back again, the application closes as expected.

Thanks for any help!

Try this instead of finish(); for exiting whole application.

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

Your previous activity which was in background might be coming in foreground by your code.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM