/**
* 监测APP是否处于前台
*/
public class ActivityLifecycleService extends Service {
private int count = 0;
public boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
/*
BACKGROUND=400 EMPTY=500 FOREGROUND=100
GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
*/
Log.i(context.getPackageName(), "此appimportace ="
+ appProcess.importance
+ ",context.getClass().getName()="
+ context.getClass().getName());
if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Log.i(context.getPackageName(), "处于后台"
+ appProcess.processName);
if (count > 10) {
//处于后台40s后重启APP
Intent newIntent = context.getPackageManager().
getLaunchIntentForPackage(PackageName);
context.startActivity(newIntent);
} else {
count++;
}
return true;
} else {
count = 0;
Log.i(context.getPackageName(), "处于前台"
+ appProcess.processName);
return false;
}
}
}
return false;
}
@Override
public void onCreate() {
super.onCreate();
executeFixedRate();
}
/**
* 以固定周期频率执行任务
*/
public void executeFixedRate() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(
new EchoServer(),
0,
1000 * 4,
TimeUnit.MILLISECONDS);
}
@SuppressLint("WrongConstant")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
flags = START_STICKY;
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
class EchoServer implements Runnable {
@Override
public void run() {
isBackground(TApplication.getInstance());
}
}
}
Android 监测APP是否处于前台
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...