1

I want to execute a function only when returning to the Application from the background.

I have included the method in onResume, and this does it to a certain extent. Problem is since onResume is fired even on creating the Activity and when returning to the activity from another activity (Ex: From pressing the back button), and the function is executed there as well.

How to avoid this and execute the function only when returning from background?

Ps: My application already has multiple places using startActivity so changing to startActivityForResult is a tedious task.

Also all my Activities are extending from a common BaseAppCompactActivity class and it's where my method is located, so this will apply to the whole application.

Edit 2: My BaseAppCompactActivity is as below with LifecycleObserver implemented now. This doesn't seem to work though.

public class BaseAppCompactActivity extends AppCompatActivity implements LifecycleObserver {
    private String TAG = BaseAppCompactActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopService();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        startService();
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
////        updateLastAccessedDate();
//    }

    private void startService() {
        startService(new Intent(this, BusinessCacheService.class));
    }

    private void stopService() {
        stopService(new Intent(this, BusinessCacheService.class));
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void updateLastAccessedDate() {
        //Do something
    }
}
Nimila Hiranya
  • 4,842
  • 10
  • 35
  • 52
  • You can use `LifecycleObserver` in Application class .. [Here it is](https://stackoverflow.com/a/48767617/4168607) Safe and Sound.. – ADM May 17 '19 at 08:29
  • Possible duplicate of [Checking if an Android application is running in the background](https://stackoverflow.com/questions/3667022/checking-if-an-android-application-is-running-in-the-background) – ADM May 17 '19 at 08:32
  • @ADM Think LifecycleObserver could solve my problem. Any Android Java code sample for this? My Kotlin knowledge is abysmal. – Nimila Hiranya May 17 '19 at 08:52

5 Answers5

3

Although its a duplicate . Here is a Java implementation i am sharing for sake of help ..

public class MyApplication extends MultiDexApplication implements LifecycleObserver {
    private boolean previouslyInBackground;
    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onAppBackgrounded() {
        previouslyInBackground=true;

    }
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onAppForegrounded() {
        if(previouslyInBackground){
           // Do your stuff Here
        }
        previouslyInBackground=false;
    }
}

Add the Gradle dependency from Lifecycle-aware components Documentation

ADM
  • 20,406
  • 11
  • 52
  • 83
1

You can use startActivityForResult instead of startActivity. Then you can catch the returning inside onActivityResult method.

MONK
  • 179
  • 2
  • 15
  • Hey, thanks @MONK. Problem is altering 'startActivity' at the moment is quite tedious since there are over 100+ instances of startActivity across the app. Any other work around? PS: All Activities are extended from a common BaseAppCompactActivity. – Nimila Hiranya May 17 '19 at 08:28
0

first set a global boolean variable like this:-

boolean isPaused = false; 

now set a methods in your activity :-

@Override
    protected void onUserLeaveHint() {
        isPaused = true;
        super.onUserLeaveHint();
    }

or in your onResume method:-

@Override
    protected void onResume() {
        if(isPaused){
         isPaused = false;

          }
super.onResume();
    }
Sandeep Malik
  • 1,972
  • 1
  • 8
  • 17
0

Do like this

add these variable in your main activity

public static boolean isAppWentToBg = true;
public static boolean isWindowFocused = false;
public static boolean isBackPressed = false;

and also add these methods

private void applicationWillEnterForeground() {
        if (isAppWentToBg) {
            isAppWentToBg = false;
//            Toast.makeText(getApplicationContext(), "App is in foreground", Toast.LENGTH_SHORT).show();
        }
    }

    public void applicationdidenterbackground() {
        if (!isWindowFocused) {
            isAppWentToBg = true;
//            Toast.makeText(getApplicationContext(), "App is Going to Background", Toast.LENGTH_SHORT).show();
        }
    }



@Override
    public void onBackPressed() {

        isBackPressed = true;
        Log.d(TAG, "onBackPressed " + isBackPressed + "" + this.getLocalClassName());
        super.onBackPressed();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        isWindowFocused = hasFocus;
        if (isBackPressed && !hasFocus) {
            isBackPressed = false;
            isWindowFocused = true;
        }

        super.onWindowFocusChanged(hasFocus);
    }


@Override
    protected void onStart() {
        Log.d(TAG, "onStart isAppWentToBg " + isAppWentToBg);
        applicationWillEnterForeground();
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop ");
        applicationdidenterbackground();
    }
Dulanga
  • 921
  • 11
  • 23
-1

What I would suggest is create a new boolean variable which say if that is created for the first time in resume and work on it.

Boolean isForeGround = true;

@Override
public void onPause() {
   super.onPause();
   isForeGround = false;
}

@Override
public void onResume() {
    super.onPause();
    if(!isForeGround){
       isForeGround = true;
       // write your code here
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Karthik
  • 1,088
  • 6
  • 17