0x00 使用Application.ActivityLifecycleCallbacks检测App运行在前台/后台
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import java.util.List;
public class ApplicationLifecycle implements Application.ActivityLifecycleCallbacks {
private Handler mHandler = new Handler();
private Runnable mCheck = new Runnable() {
@Override
public void run() {
Log.e("ApplicationLifecycle", "check task exec; mCounter=" + mCounter);
if (mCounter == 0) {
Log.e("ApplicationLifecycle", "check task exec; get runningAppProcessInfo.");
final ActivityManager am = (ActivityManager) mAppContext.getSystemService(Context.ACTIVITY_SERVICE);
// NOTE: getRunningAppProcess() ONLY GIVE YOU THE PROCESS OF YOUR OWN PACKAGE IN ANDROID M
// BUT THAT'S ENOUGH HERE
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
boolean foreground = false;
for (ActivityManager.RunningAppProcessInfo ai : am.getRunningAppProcesses()) {
// KILL OTHER PROCESS OF MINE
if (ai.uid == android.os.Process.myUid()
&& ai.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Log.e("ApplicationLifecycle", ai.processName + " importance is IMPORTANCE_FOREGROUND.");
foreground = true;
break;
}
}
if (foreground) {
Log.e("ApplicationLifecycle", "check task exec; background=false");
} else {
Log.e("ApplicationLifecycle", "check task exec; background=true");
}
}
}
};
private int mCounter = 0;
private Context mAppContext = null;
public ApplicationLifecycle(Context context) {
mAppContext = context.getApplicationContext();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
mCounter++;
Log.e("ApplicationLifecycle", "onActivityResumed mCounter=" + mCounter);
mHandler.removeCallbacks(mCheck);
}
@Override
public void onActivityPaused(Activity activity) {
mCounter--;
Log.e("ApplicationLifecycle", "onActivityPaused post check task; mCounter=" + mCounter);
mHandler.removeCallbacks(mCheck);
mHandler.postDelayed(mCheck, 2000);
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
0x01 杀进程的各种方法
if (Build.VERSION.SDK_INT >= 21) {
finishAndRemoveTask();
}
if (Build.VERSION.SDK_INT >= 16) {
finishAffinity();
}
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(getPackageName());
android.os.Process.killProcess(android.os.Process.myPid());// kill process
System.exit(-1);