I have an Android Activity that sometimes is started by the user and sometimes is started from a service. When started from the service (by sending an Intent that is received by my Activities onNewIntent() callback) I just want it to update its screen if already running but not to start running if it was not already running.
My attempts to achieve this have been arranged around having a boolean set in my Activity during onResume() and cleared during onPause() but I noticed that onPause() is always called before my Activity receives its onNewIntent() and so the value is always false.
For those not familiar with the event sequence it is as follows :
startActivity(myIntent); // Called from service with Intent Extra indicating that fact
onPause(); // Overriden method for my Activity
onNewIntent(Intent myIntent); // Overriden method for my Activity
onResume(); // Overriden method for my Activity
My understanding from reading around is that this behaviour is fixed and intended and there is no way around it. One suggestion I saw was to time the interval between onPause() and onNewIntent() being called and use that as an estimate for whether my Activity had been running immediately before onNewIntent() but I was hoping someone here might know a better way ?
I am actually using Fragments instead of plain Activities but that does not change anything of significance.
Thanks,
If you want just to know if your activity already in foreground then will try this snippet:
class MyActivity extends Activity {
private boolean isLaunched;
@Override
protected void onStart() {
super.onStart();
isLaunched = true;
}
@Override
protected void onStop() {
super.onStop();
isLaunched = false;
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (isLaunched) {
//todo
}
else
{
//somethin here
}
}
}