Link: http://zengrong.net/post/1680.htm
An Android app contains a background program that regularly connects to the server to push custom information. However, when the application is in the foreground, there is no need for the background program to connect to the server. This saves network resources and saves power.
How do I know if the application is on the frontend?
Most of the methods found on the internet use the following code:
123456 |
Activitymanager AM = (activitymanager) This. getsystemservice (activity_service); // obtain the task list <activitymanager. runningtaskinfo> taskinfo = aM. getrunningtasks (1); log. D ("topactivity", "current activity:" + taskinfo. get (0 ). topactivity. getclassname (); componentname componentinfo = taskinfo. get (0 ). topactivity; componentinfo. getpackagename (); |
However, Google does not recommend this method after reading the android documentation:
This shoshould never be used for core logic in an application, such as deciding between different behaviors based on the information found here. such uses are not supported, and will likely break in the future. for example, if multiple applications can be actively running at the same time, assumptions made about the meaning of the data here for purposes of control flow will be incorrect.
In addition, this method also requires settingandroid.permission.GET_TASKS
Permission.
Therefore, I have to find a more appropriate way to do this. In the end, I found this method getrunningappprocesses () and it does not need to add special permissions.
The following is the sample code:
1234567891011121314151617181920212223 |
/*** Return whether the current application is in the foreground display status * @ Param $ packagename * @ return */private Boolean istopactivity (string $ packagename) {// _ context is a saved context activitymanager _ am = (activitymanager) _ context. getapplicationcontext (). getsystemservice (context. activity_service); List <activitymanager. runningappprocessinfo> _ list = _ am. getrunningappprocesses (); If (_ list. size () = 0) return false; For (activitymanager. runningappprocessinfo _ process :__ list) {log. D (gettag (), integer. tostring (_ process. importance); log. D (gettag () ,__ process. processname); If (_ process. importance = activitymanager. runningappprocessinfo. importance_foreground & _ process. processname. equals ($ packagename) {return true ;}} return false ;} |
How do I know whether an activity is on the frontend?