Susomrof
Susomrof

Reputation: 234

Calling finish() in onStop()

What happens when finish() method is called in onStop() method?

Does it causes anr : means it calls

onPause()->onStop()->finish()->onPause()....

or it finishes the activity : means it calls directly

onDestroy()

Actually, I want to finish my activity when it is completely invisible.

EDIT:

See this scenario, I launch an activity B whose layout height and width is smaller than activity A, so activity A is partially visible and when I press the home button activity A becomes completely invisible. At this point I want to close activity A, so that it do not call onRestart().

Thanks in advance.

Upvotes: 2

Views: 8612

Answers (3)

Satyaki Mukherjee
Satyaki Mukherjee

Reputation: 2879

It will be best way in your case to call finish() ;

Thanks

Upvotes: -1

Gopal Gopi
Gopal Gopi

Reputation: 11131

according to your scenario, maintain one flag in MainActivity indicating that other Activity is launched or not? and make sure yourself to finish MainActivity or not based on that flag ...

this may help you...

public class MyActivity extends Activity {
    private boolean isSecondActivityLaunched;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isSecondActivityLaunched = false;
    }

    public void onClick(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
        isSecondActivityLaunched = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(!isSecondActivityLaunched) {
            finish();
        }
    }
}

Upvotes: 0

PratikGandhi
PratikGandhi

Reputation: 173

It finishes the activity and onDestroy() is called. If you want to finish your activity when it is invisible then you should call finish() in onStop().

Upvotes: 3

Related Questions