Android Monitor app goes backstage or switch to foreground scenario comparison

Source: Internet
Author: User

In our development process, we often encounter the need to judge the app to enter the background, or switch to the foreground of the situation. For example, we want to judge the app to switch to the foreground, display an unlock interface, require the user to enter the unlock password to continue operation, we want to judge the app to switch to the background, log the log, or when the user switches back to the foreground, we want to refresh the page data and so on ...

Android monitors the app front and back of the program a lot (this is still rooted in the Android provides a rich API and strong architectural support, hehe ~), such as can be provided through the Activitymanager getrunningappprocesses () Get the app currently running on your system to determine if the app is in the foreground. Or click the Home button to determine if the app is back in the background. The following will be for the author's known scenarios, comparative analysis.

Scenario I: Using Activitymanager's Runningappprocessinfo class
Activitymanager plays a very important role in the entire system, primarily providing interfaces for activity interactions that are running in the system, where the Runningappprocessinfo class encapsulates the running process information, It also contains the package name of the running app, so we can activitymanager.getrunningappprocesses () get a list of currently running apps and compare the package name to determine if the app is running in the foreground.

This interrupts, Activitymanager framework is a very important part of the Android system, at a later time, I will learn to organize the analysis of Activitymanager framework.

Back here, some of the key codes are given below.

 /** App front and back status*/     PublicBoolean isforeground =false; @Overrideprotected voidOnresume () {...if(Isforeground = =false) {            //switch from background to foregroundIsforeground =true; }} @Overrideprotected voidOnPause () {...if(!Isapponforeground ()) {            //switch from foreground to backgroundIsforeground =false; }    }    /** * determine if the app is in the foreground * * @return*/     PublicBoolean isapponforeground () {Activitymanager Activitymanager=(Activitymanager) Getapplicationcontext (). Getsystemservice (Context.activity_service); String PackageName=Getapplicationcontext (). Getpackagename (); /** * Get all the apps running on your Android device*/List<RunningAppProcessInfo> appprocesses =Activitymanager. getrunningappprocesses (); if(Appprocesses = =NULL)            return false;  for(Runningappprocessinfo appprocess:appprocesses) {//The name of the process, the this object was associated with.            if(AppProcess.processName.equals (PackageName)&& Appprocess.importance = =runningappprocessinfo.importance_foreground) {                return true; }        }         return false; }

Summary: Use Activitymanager to get a list of currently running apps, and then determine whether our app is in the foreground and basically meet our expected needs. But if you put the above code in every activity, or activity base class, it's pretty expensive. And also, Activitymanager through. getrunningappprocesses () to get the current run list of the method, after 5.0 has been deprecated off .... (Heart steeds ... )

Scenario Two: Listen to the home button click

Speaking of the home button monitoring, is also a stem inside Android. This seemingly simple function, in fact, is very tortuous, which is very much related to the design of the Android system. When the home button is clicked, a system broadcast will be issued, after the system received this broadcast, will be in the framework layer to do a series of actions to back the current app to the background, and then the event consumption is not passed to the application layer, so this time onkeydown event also received. The official explanation is that--"Home key." This key was handled by the framework and was never delivered to applications. " In fact, this is also for the sake of security, otherwise every app will listen to the home button, and then disable the response, not all become rogue software.

The official does not support, but this is difficult to our omnipotent siege lions, after all, there are many want our regular developers, or need to listen to the home button to do some such as write log operations. Google Baidu on the internet will have a lot of similar solutions, here will not expand. (But you can recommend it here.)

Summary: We can hear the home button click, of course, we know the app is in the foreground or backstage. But after all, this program is based on the premise that the official does not support, and home button monitoring in many devices will have compatibility issues, so we do not recommend this.

Scenario Three: Use Activitylifecyclecallbacks to monitor the life cycle of all activity

By listening to all the activity's onstart, OnStop calls, and then counting whether all the activity is currently called OnStop, you can actually tell the app is in the background, but let's rewrite each activity's onstop, and add this strange code, it is not very elegant, even in the activity base class inside the unified write, the day if you forget or do not need to inherit the activity of the base class, it is not very good.

Therefore, here is recommended a new interface Activitylifecyclecallbacks, said the new is not new, in fact, early in the API (Android 4.0) has been launched. The Activitylifecyclecallbacks interface is inside the application class, so we need to inherit the application ourselves, customize a myapplication, and then register the interface. Activitylifecyclecallbacks provides application with monitoring of all activity lifecycles, So we define a variable by rewriting Activitylifecyclecallbacks's onactivitystarted and onactivitystopped methods to count the current number of activity in the foreground.

  /** * Current number of acitity*/    Private intActivityaount =0; @Override Public voidonCreate () {... registeractivitylifecyclecallbacks (activitylifecyclecallbacks);     ......    } /** Activity lifecycle monitor for monitoring app front and back status switching*/activitylifecyclecallbacks activitylifecyclecallbacks=Newactivitylifecyclecallbacks () {@Override Public voidonactivitycreated (activity activity, Bundle savedinstancestate) {} @Override Public voidonactivitystarted (activity activity) {//if (Activityaount = = 0) {//                //app back to front desk//Isforeground = true;//            }activityaount++; } @Override Public voidonactivityresumed (activity activity) {} @Override Public voidonactivitypaused (activity activity) {} @Override Public voidonactivitystopped (activity activity) {Activityaount--; if(Activityaount = =0) {Isforeground=false; }} @Override Public voidonactivitysaveinstancestate (activity activity, Bundle outstate) {} @Override Public voidonactivitydestroyed (activity activity) {}};

The above code is written in MyApplication. How, is not very simple and quick! and accurate.

Summarize:
1, the use of Activitymanager Runningappprocessinfo class, direct rudeness, the official abandonment, not recommended;
2, listen to the home button click, the official does not support, poor compatibility, instability, not recommended;
3, the use of activitylifecyclecallbacks monitoring all activity life cycle, the official designated drinks, oh, no, official designated interface, strongly recommended! We extrapolate, with activitylifecyclecallbacks monitoring, we can control our activity stack and even log statistics ... It's still very powerful to think about.

PS: Although the use of the Activitylifecyclecallbacks interface to monitor the optimal scheme, but this is after 4.0 of the product, so for 4.0 or less, you can consider increasing the scenario of a judgment.

Android Monitor app goes backstage or switch to foreground scenario comparison

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.