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
}
}