I'm actually using this code to check if the app in the onPause is going to the background or not.
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningTaskInfo> tasks = am.getRunningTasks( 1 );
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get( 0 ).topActivity;
String name = LockScreenActivity.class.getName();
String topAPN = topActivity.getPackageName();
String conAPN = context.getPackageName();
if (topActivity.getClassName().equals( name ) || !topActivity.getPackageName().equals( context.getPackageName() )) {
return true;
}
}
return false;
}
This code has worked pretty well until now with Android 4.4. If now I check topAPN
and conAPN
they are equal (and they are always not equal when the app is sent to background on android <= 4.3).
Do you know how to solve this problem? Has something changed?
I was facing the same issue.I solved it for the new versions.Just use this code
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
And in onPause method call this function this way
@Override
protected void onPause() {
super.onPause();
handler.sendMessage(new Message());
}
Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (DeviceManager.isApplicationSentToBackground(getApplicationContext())) {
paused = true;
}
return false;
}
});
I dont know the excat reason but may be because of diff thread in handler i m getting the correct value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With