1. How to tell if the program is running in the background
/*** To determine if the current application is running in the background, use the program to declare permissions Android.permission.GET_TASKS *@paramContext Context *@returnTrue indicates that the current application is running in the background. False to run in foreground*/ Public Static BooleanIsapplicationbroughttobackground (Context context) {Activitymanager am=(Activitymanager) Context.getsystemservice (Context.activity_service); List<RunningTaskInfo> tasks = am.getrunningtasks (1); if(Tasks! =NULL&&!Tasks.isempty ()) {componentname topactivity= Tasks.get (0). topactivity; if(!topactivity.getpackagename (). Equals (Context.getpackagename ())) { return true; } } return false;}
- In the activity of the OnStop method to determine whether the current application is running in the background, while using a member variable to record whether the activity is the background, in the Onresume method to determine whether the variables in the background of the logger is true, True indicates that the program is now switching from the background to the foreground, when it is time to refresh the data
/*** Used to record whether the current application is running in the background, this only works for an activity, if you want all the * activity to know the program from backstage to the foreground, this time to get a base class baseactivity, in the * baseactivi Ty to execute the code and let the other activity inherit the baseactivity. and to turn the * isapplicationbroughttobackground into static. * Then do not execute Isapplicationbroughttobackground = False in the Onresume method, so that other * activity in the Onresume method is judged when the application is switching from the background to the foreground, Do not worry that this will lead to Isapplicationbroughttobackground can not be restored to false, because in the OnStop method, we * determined that if the program is not the background, it will Isapplicationbroughttobac Kground turns false.*/ Private BooleanIsapplicationbroughttobackground; @Overrideprotected voidOnStop () {Super. OnStop (); if(Isapplicationbroughttobackground ( This)) { //program backstage.Logutil.i (TAG, "Backstage ..."); Isapplicationbroughttobackground=true; }Else{logutil.i (TAG,"The Wood has backstage"); Isapplicationbroughttobackground=false; } } protected voidOnresume () {Super. Onresume (); if(isapplicationbroughttobackground) {//switching from the background to the foreground.Logutil.i (TAG, "switch from background to foreground, refresh data")); Loadfocusinfodata (); } isapplicationbroughttobackground=false; };
Refresh data after applying background wakeup