Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Is onPause() guaranteed to be called after finish()?

Tags:

java

android

Couldn't find a solid answer to this anywhere. I have a method where finish() is being called, and onPause() is called afterward.

Is onPause() guaranteed to be called after a call to finish() ?

like image 810
Kacy Avatar asked Feb 28 '15 02:02

Kacy


People also ask

Is onPause always called?

Even if your activity slips into the background when another activity starts or when the screen switches off, onPause() is always called even if the other two methods aren't called. So even if activity ceases, onPause() will be called and your thread will be killed.

When onPause method is called in Android?

onPause. Called when the Activity is still partially visible, but the user is probably navigating away from your Activity entirely (in which case onStop will be called next). For example, when the user taps the Home button, the system calls onPause and onStop in quick succession on your Activity .

What does finish () do in Android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

What happens when you call finish () inside onCreate ()?

You can call finish() from within this function, in which case onDestroy() will be immediately called after onCreate(Bundle) without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.


1 Answers

Android will generally call onPause() if you call finish() at some point during your Activity's lifecycle unless you call finish() in your onCreate().

public class MainActivity extends ActionBarActivity {

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



  @Override
  protected void onPause() {
    super.onPause();
    Log.d(TAG, "onPause");
  }

  @Override
  protected void onStop() {
    super.onStop();
    Log.d(TAG, "onStop");
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy");
  }
}

Run, and observe that your log will only contain "onDestroy". Call finish() almost anywhere else and you'll see onPause() called.

like image 58
Michael Powell Avatar answered Dec 07 '22 22:12

Michael Powell