开发者

How I can detect that my Android app on the foreground?

开发者 https://www.devze.com 2023-03-13 23:38 出处:网络
I\'m trying to know my or no application on the foreground using the next code from BroadcastReceiver:

I'm trying to know my or no application on the foreground using the next code from BroadcastReceiver:

boolean inForeground = false;
ActivityManager actMngr = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
    if (context.getPackageName().equals(pi.processName)) {
      inForeground = pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
    }
}

But this code always return true, even when my application in background. I found next solution:

if (actMngr.getRunningTasks(开发者_JS百科1).get(0).topActivity.getPackageName().equals(context.getPackageName())){
  Log.d(TAG, "My");
} else {
  Log.d(TAG, "Not my");
}

Is this code correct or not? Or maybe somebody know more simple variant? Thanks!


The most direct way is to track your foreground status using onResume() and onPause(). Refer to the Activity lifecycle model.

0

精彩评论

暂无评论...
验证码 换一张
取 消