简体   繁体   中英

How to finish my activity when I have 2 scenarios

I have an activity that makes something and then starts another activity. The first activity has to finish after creating the second. In this case I want it only to end with default onDestroy(). But if user presses back key (Hardware one) while first activity isn't done I want it to call a function before finishing. Is there any gentle way to achieve that? I think about overriding default action for back key but is it the only and the most elegant solution?

You can declare a flag in the first activity that indicates whether it is finished.

public class Activity1 extends Activity {
    private boolean workDone = false;

    . . .

    @Override
    protected void onDestroy() {
        if (!workDone) {
            specialFunction();
        }
        super.onDestroy();
    }
}

Then somewhere in Activity1 , when it has completed its necessary work, just set workDone = true .

Overriding onBackPressed method is OK.

public void onBackPressed ()

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

http://developer.android.com/reference/android/app/Activity.html#onBackPressed()


public void onBackPressed() {
    // do something.
    super.onBackPressed();
}

Well you can override the onBackButtonPressed() and then call the super.onBackButtonPressed, so you don't miss on anything the super class does, but you can add stuff to the call. Same goes for onDestroy()

in this example, utask is an asynchronous task I want to kill.

    @Override
    protected void onStop() {
        utask.cancel(true);
        super.onStop();

    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        utask.cancel(true);
        super.onBackPressed();

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        utask.cancel(true);
        super.onDestroy();

    }

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