当点击Home键或其他原因造成应用进入后台,对于金融类App此时需要对其状态进行判断,进而做出相对于操作(一般吐司提示)。
public class MyApplication extends BaseApplication {
@Override
public void onCreate() {
......
registerActivityLifecycleCallbacks(new ActivityLifecycleListener());
}
}
给Application注册监听,当每个Activity都会触发它的回调。
public class ActivityLifecycleListener implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
if (isBackground(activity.getApplicationContext())) {
//只对非正常退出做处理
if (MyApplication.illegal) {
Toast.makeText(activity.getApplicationContext(), "站住!别走~~", Toast.LENGTH_LONG).show();
} else {
MyApplication.illegal = true;
}
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
public static 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
*/
if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Log.i(context.getPackageName(), "处于后台"
+ appProcess.processName);
return true;
} else {
Log.i(context.getPackageName(), "处于前台"
+ appProcess.processName);
return false;
}
}
}
return false;
}
}