標籤:安卓 密碼鎖
功能:1.應用程式程式中設定了密碼鎖,每當使用者開啟應用時,要彈出密碼輸入介面;2.當使用者按住home鍵,將程式隱在後台而非退出,經過一段時間後,再重新啟動,也要彈出密碼輸入介面;3.當應用在前台的時候,使用者按住power電源鍵,關閉螢幕後,再點亮螢幕,這個時候也要彈出密碼輸入介面
實現方式:1.針對功能1,每次啟動應用進入主介面時,判斷是否需要彈出密碼輸入介面;2.關鍵點在於怎麼判斷程式是否處在前台跟後台。 判斷方法:
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;}
其主要原理是:擷取當前正在啟動並執行所有進程,根據進程名字進行逐一比較(預設應用程式進程名字為包名),並且當前進程的 importance 為IMPORTANCE_FOREGROUND,及該進程處在前台。
在Activity中加一個boolean變數 mIsActive = true,預設為true。
在所有Activity的onStop中做一次判斷:
protected void onStop() { super.onStop(); if(!isAppOnForeground(this)) { mIsActive = false; }}
在相應Activity的onRestart()中判斷:
protected void onRestart() { if(!mIsActive) { mIsActive = true; //彈出密碼框輸入介面 //.………... }}
3.監聽鎖屏廣播:ACTION_SCREEN_ON在Application裡註冊一個廣播:
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)) { //使用者關閉螢幕 }}
在自己的Application的onCreate()裡註冊該BroadcastReceiverd的執行個體:
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);}
注意點:在收到螢幕點亮通知的時候,要判斷應用程式是否在前台,如果不在前台,則不要把密碼鎖介面掉出來。在這個時候調用isAppOnForeground()方法,發現會返回true,也就是程式在收到這個廣播的時候,系統認為應用跑到foreground來了。解決方案:在Application中設定一個變數IS_FOREGROUND,在Activity的onCreate()、onStop()、onRestart()中進行判斷並設定該變數的值。
安卓應用程式密碼鎖的實現