Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get state of activity (paused / resumed)

I am using a LoaderManager to get some data and when it finishes a child fragment should be shown. In some cases this happens when the activity is already in paused state and can not perform the fragment transaction.

Is there a way to get the current state of the activity (seems to have a mResume flag)? Or do I have to maintain my own boolean?

like image 742
Gunnar Bernstein Avatar asked Mar 28 '15 18:03

Gunnar Bernstein


People also ask

When an activity is in the paused state the activity?

States of An Activity Paused – An activity is in a paused state when the activity is visible but not in focus. Stopped – An activity is in a stopped state when it's no longer visible. It is still in memory, but it could be destroyed by the android runtime, as “stopped” activities are generally considered low priority.

How do you pause and resume activity on android?

During an activity, press and hold left to stop the clock and pause your activity. To restart the activity again, press right.

When a migration activity is paused by the user what methods can be used to resume the activity?

Resume Your Activity When the user resumes your activity from the Paused state, the system calls the onResume() method. Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time.


2 Answers

The new Architecture Components allow you to do it with:

this.getLifecycle().getCurrentState()
like image 123
MorZa Avatar answered Oct 13 '22 00:10

MorZa


A quick look in the Activity source code indicates that the Activity class does keep track on the resume state with the member mResumed. But since mResume is not public and isResumed() is hidden, we can't use them.

You can have a simple solution to provide you with that information for all your classes. Simply create a base Activity class that store the state. For example:

public class ActivityBase extends Activity {

    private boolean mIsResumed = false;

    @Override
    public void onResume() {
        super.onResume()
        mIsResumed = true;
    }

    @Override
    public void onPaused() {
        super.onPaused()
        mIsResumed = false;
    }

    public boolean isResumed() {
        return mIsResumed
    }

}

Simply extend this class with your class:

public class MyActivity extends ActivityBase {

    private void onLoadDone() {
        if (isResumed()) {
            // Show the fragment
        }
    }

}
like image 33
Eyal Biran Avatar answered Oct 12 '22 23:10

Eyal Biran