Android determines the frontend and backend status of a program

Source: Internet
Author: User

AppStatusService
Java code
Package org. wp. activity;
 
Import java. util. List;
 
Import android. app. ActivityManager;
Import android. app. ActivityManager. RunningAppProcessInfo;
Import android. app. Service;
Import android. content. Context;
Import android. content. Intent;
Import android. OS. IBinder;
Import android. util. Log;
 
Public class AppStatusService extends Service {
Private static final String TAG = "AppStatusService ";
Private ActivityManager activityManager;
Private String packageName;
 
@ Override
Public IBinder onBind (Intent intent ){
Return null;
}
 
@ Override
Public int onStartCommand (Intent intent, int flags, int startId ){
ActivityManager = (ActivityManager) this. getSystemService (Context. ACTIVITY_SERVICE );
PackageName = this. getPackageName ();
New Thread (){
Public void run (){
Try {
While (true ){
Thread. sleep (1000 );
If (isAppOnForeground ()){
Log. I (TAG, "true ");
} Else {
Log. I (TAG, "false ");
}
}
} Catch (Exception e ){
E. printStackTrace ();
}
}
}. Start ();
Return super. onStartCommand (intent, flags, startId );
}
 
Private boolean isAppOnForeground (){
// Returns a list of application processes that are running on the device
List <RunningAppProcessInfo> appProcesses = activityManager. getRunningAppProcesses ();
If (appProcesses = null) return false;
For (RunningAppProcessInfo appProcess: appProcesses ){
// Importance:
// The relative importance level that the system places
// On this process.
// May be one of IMPORTANCE_FOREGROUND, IMPORTANCE_VISIBLE,
// IMPORTANCE_SERVICE, IMPORTANCE_BACKGROUND, or IMPORTANCE_EMPTY.
// These constants are numbered so that "more important" values are
// Always smaller than "less important" values.
// ProcessName:
// The name of the process that this object is associated.
If (appProcess. processName. equals (packageName)
& AppProcess. importance = RunningAppProcessInfo. IMPORTANCE_FOREGROUND ){
Return true;
}
}
Return false;
}
}

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.