Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if app is in background

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?

like image 449
StErMi Avatar asked Nov 11 '13 15:11

StErMi


1 Answers

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

like image 66
sheetal Avatar answered Sep 28 '22 22:09

sheetal