public static boolean isAppOnForeground(Context context) { ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); String packageName = context.getApplicationContext().getPackageName(); List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if(appProcesses == null) return false; for(RunningAppProcessInfo appProcess : appProcesses) { if(appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } return false; }
protected void onStop() { super.onStop(); if(!isAppOnForeground(this)) { mIsActive = false; } }
protected void onRestart() { if(!mIsActive) { mIsActive = true; //弹出密码框输入界面 //.………... } }
public static boolean IS_FOREGROUND = false; public class ScreenActionReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_SCREEN_ON)) { //用户点亮屏幕 //判断是否需要弹出密码锁来 if(IS_FOREGROUND) { //如果应用程序恰好处在前台,则弹出密码锁界面来 } } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { //用户关闭屏幕 } }
if(mScreenActionReceiver == null) { mScreenActionReceiver = new ScreenActionReceiver(); IntentFilter screenfilter = new IntentFilter(); screenfilter.addAction(Intent.ACTION_SCREEN_OFF); screenfilter.addAction(Intent.ACTION_SCREEN_ON); registerReceiver(mScreenActionReceiver, screenfilter); }
原文地址:http://blog.csdn.net/kaka123ac/article/details/42124569