Hi guys I’m using this method to check if my app is in background or not:
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
for( RunningTaskInfo rti: tasks ) {
ComponentName cn = rti.topActivity;
LogHelper.i(TAG, "Component Name: " + cn.getPackageName() );
}
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
I’m calling this method in my Activity onPause, onStop, onDestroy
These is my results:
when I’m in my activity and I click the android-home-button it follow this flow:
onPause -> is in background? true
onStop -> is in background? true
and it’s all perfect.
The problem is when I click the android-back-button that from th activity goes back to the android home. This is the flow:
onPause -> is in background? false
onStop -> is in background? false
onDestroy -> is in background? false
If you check the code I have a Log cat stamp and it always (in the back-button case) stamp this:
03-29 00:46:39.324: I/DFFramework(15344): MusicUtils – Component Name: my-activity-name
This means that my activity is not in the background.
What can I do?
UPDATE:
I’m adding more info about my scenario. I’m developing a Music Player so I’ve to catch this kind of event in order to start my foreground audio service if the app is closed but the music is still playing (otherwise the music will be paused).
So I’ve to catch when the app is in background (like when you click the android-home-button) or when you are closing the application (for example when you click android-back-button).
So this is how I solved (to emulate the Google Music Player behaviour)
As I said I was looking for 2 kinds of event:
when my app goes in background
when user tap androd-back-button and goes to the android home (app is destroyed)
So this is my onPause done in my super activity
First of all I check if the app is in background with isApplicationSentToBackground (the source code in the question body).
If the app is not in the background there are 2 reasons:
So to catch the second event I check if the user pressed the back button
And if they bakc-key is pressed I check if this activity is the latest one (so after the current activity is destroyed my app will be destroyed!)
To check this I get the count number returned by MusicUtils.getActiviesApplicationInBackStack(this)
I hope this answer help someone in my same problem 🙂 I know that this is a strange scenario but it’s always a good think to share problems, thoughts and code 🙂