23

I'm trying to understand the difference between onPause and onStop.

I've read all the different forums but I still am not clear about the difference. I've created a simple app to try and test when which method gets called. For that I've simply placed loggers in each method.

From my trials -

  1. Popups do not call either method
  2. Switching to another activity calls both methods
  3. Pulling down the notification bar calls neither method

I've only seen either both methods being called in quick succession or neither getting called at all. I'm trying to find scenarios where onPause gets called but onStop doesn't.

The purpose is to understand whether defining onPause is even required. If the scenarios in which only onPause gets called are so rare, it doesn't even make sense to write separate code for onPause. Shouldn't writing onStop be sufficient?

public class LifecycleActivity extends ActionBarActivity {

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Rachit", "In Destroy Method");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle);
        Log.d("Rachit", "In Create Method");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Rachit", "In Start Method");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Rachit", "In Resume Method");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Rachit", "In Pause Method");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Rachit", "In Restart Method");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Rachit", "In Stop Method");
    }
}
Rachit
  • 3,173
  • 3
  • 28
  • 45

11 Answers11

29

I figured this out a while later, but forgot to post my answer here.

The instance where I noticed that onPause() was called, without an immediate subsequent call to onStop() was when I got a notification from a different application when a different app was open on my phone.

For example, say you have Facebook running on your phone currently. If you receive a notification from WhatsApp (in the pop-up dialog box), your Facebook activity will be paused. If you close the WhatsApp pop-up during this time, the Facebook Activity will get Resumed. On the other hand, if you open WhatsApp from the pop-up message, your Facebook Activity will be stopped.

Rachit
  • 3,173
  • 3
  • 28
  • 45
9

This scenario occurs when you start a DialogActivity from your current activity, then the onPause() of current activity is called and after coming on current Activity the onResume() is called.

For more information, please see Developer Docs.

Sufian
  • 6,405
  • 16
  • 66
  • 120
Ishwar Verma
  • 119
  • 1
  • 5
  • FWIW [this answer](http://stackoverflow.com/a/7384782/1276636) by Android framework engineer is a great read. `DialogActivity` in the answer by Ishwar Verma is an Activity which applies the style of a dialog, so basically it is an Activity which looks like a dialog. – Sufian Nov 28 '16 at 09:39
7

Activity A --> Activity B If B is transparent, A' onPause will be called but no onStop.

Eric
  • 71
  • 1
  • 3
4

The official Android Developers page you can see all the information relating to these two states of activity

onPause() (http://developer.android.com/training/basics/activity-lifecycle/pausing.html)

When the system calls onPause() for your activity, it technically means your activity is still partially visible, but most often is an indication that the user is leaving the activity and it will soon enter the Stopped state. You should usually use the onPause() callback to:

Stop animations or other ongoing actions that could consume CPU. Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email). Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.

Generally, you should not use onPause() to store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage within onPause() is when you're certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during onPause(), such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during onStop()).

You should keep the amount of operations done in the onPause() method relatively simple in order to allow for a speedy transition to the user's next destination if your activity is actually being stopped.

Note: When your activity is paused, the Activity instance is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state.

onStop() (http://developer.android.com/training/basics/activity-lifecycle/stopping.html)

When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.

Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.

When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don't need to save and restore it.

Note: Even if the system destroys your activity while it's stopped, it still retains the state of the View objects (such as text in an EditText) in a Bundle (a blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity (the next lesson talks more about using a Bundle to save other state data in case your activity is destroyed and recreated).

  • Yes, but I've yet to find an instance where onPause gets called but onStop doesn't. If they are always called together, wouldn't it make more sense just to have one method and save data or release resources in that? – Rachit Jun 30 '15 at 18:15
  • The onStop method is called only when the activity is not completely visible, whereas the onPause method is called when the activity is still visible but has remained in the background. For example, when you show a Dialog. The behind the Activity Dialog is in onPause, but if you open a new activity, is passed by the method of onPause and onStop @Rachit – Juanvi Bolufer Jun 30 '15 at 18:22
  • 1
    That's the problem. A dialog does not call onPause. I've tried getting Dialog boxes, but even then the onPause doesn't get called. – Rachit Jun 30 '15 at 18:24
  • Can you show me a piece of your code to help better? – Juanvi Bolufer Jun 30 '15 at 18:30
  • You can see the answer here: http://stackoverflow.com/questions/7240916/android-under-what-circumstances-would-a-dialog-appearing-cause-onpause-to-be A Dialog is not an activity, that is why the activity does not pass the background and does not call the onPause and onStop methods. – Juanvi Bolufer Jun 30 '15 at 19:01
  • Exactly, so when will only onPause be called? – Rachit Jun 30 '15 at 19:37
  • I think it depends on the use case can implement a method, both or none. – Juanvi Bolufer Jun 30 '15 at 20:12
  • 1
    @Rachit Only `onPause()` will be called if you use a `DialogActivity`. Take a look at the answer provided by @Ishwar Verma. – Anyonymous2324 Mar 03 '16 at 08:39
3

My test case result:

For the two activities below, when starting C4_SecondActivity from MainActivity, for MainActivity, its onPause called but not onStop.

<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity
    android:name=".C4_SecondActivity"
    android:label="@string/title_activity_c4__second"
    android:theme="@style/Theme.AppCompat.Dialog">
</activity>
LiuWenbin_NO.
  • 1,216
  • 1
  • 16
  • 25
3

One scenario will be when there is a dialog box visible on the screen then also only onPause() will be called and not onStop().

0

When we start dialog activity from current Activity at that time only onPause() will be called. Ex: Let's say we have activity A and B. Now Activity B is dialog activity and activity A is normal Activity. when we start activity B from activity A, then activity A's onPause() will be called and activity B'sonCreate(),onStart() and onResume() will be called.Please check below url for sample code sample code

Narendra
  • 1,010
  • 1
  • 12
  • 11
0

There is another way to do this. lets take an scenario where you activity launch mode is singletask and create a notification from it and trigger it and call the same pending intent again then onresume will be called post to on pause.

public class MainActivity extends AppCompatActivity {

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

    private final static String TAG = "TestOne";

    public  void sendNotification(){
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this);

    //Create the intent that’ll fire when the user taps the notification//

    Intent i = new Intent(MainActivity.this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);


    mBuilder.setContentIntent(pendingIntent);

    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle("My notification");
    mBuilder.setContentText("Hello World!");

    NotificationManager mNotificationManager =

            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(001, mBuilder.build());

} 

Manifest :

    <activity android:name=".MainActivity"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Main2Activity"></activity>
Rachit
  • 3,173
  • 3
  • 28
  • 45
0

One scenario, the onPause() method is called, but the onStop() method is not called when requesting runtime permission

Can try by this code

private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->

}

fun requestCameraPermission() {
    requestPermissionLauncher.launch(android.Manifest.permission.CAMERA)
}

Seem like activity onPause() but not onStop() because the Permission Request is a transparent activity.
Also, this activity is not belong to the app, so our app will be in background while requesting permission

Linh
  • 57,942
  • 23
  • 262
  • 279
-1

onPause() method of an activity is call when you receive a phone call. Otherwise in lots of cases onPause() is always call with onStop(). Example like when you press home button, call another intent and more like when your activity is in background.

Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
-1
Whenever we do Split window than onPause will be called alone 
In Split window onStop will not be Called.
sharma_kunal
  • 2,152
  • 1
  • 28
  • 28