Checking if an Android application is running in the background

前端 未结 30 2646
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 07:08

    Since Android API 16 there is a simple way to check if app is in foreground. It may not be foolproof, but no methods on Android are foolproof. This method is good enough to use when your service receives update from server and has to decide whether to show notification, or not (because if UI is foreground, user will notice the update without notification).

    RunningAppProcessInfo myProcess = new RunningAppProcessInfo();
    ActivityManager.getMyMemoryState(myProcess);
    isInBackground = myProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
    

提交回复
热议问题