Android小视频app源码进入程序后启动手势密码的相关代码
1,我们先来分析下第一种方式,进入APP 时启动手势密码
进入app 时启动手势密码,有一个关键的知识点,前后台切换,如何判断app 应用做了前后台切换了呢?
(1) 使用ProcessLifecycleOmner
ProcessLifecycleOwner
该类提供了整个 app 进程的 lifecycle。
可以将其视为所有 activity 的 LifecycleOwner ,其中 Lifecycle.Event.ON_START 代表app 进入前台,而 Lifecycle.Event.ON_STOP 代表app 进入后台。当然(Lifecycle.Event.On_RESUME 和 Lifecycle.Event.ON_PAUSE 也可以分别代表进入前台和后台)。
ProcessLifecycleOwner.get().lifecycle.addObserver(object:LifecycleObserver{ @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onForeground(){ EasyLog.e(TAG,"== onForeground==") } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onBackground(){ EasyLog.e(TAG,"== onBackground==") } });
ProcessLifecycle 能很好的监听前后台切换,但是 不太适合做手势密码的前后台切换,首先首页和登录页是不需要弹出手势密码的,这些页面要过滤,ProcessLifecycle 不好做到这一点。下面看第二种方法。
(2)使用 lifecycleCallbacks接口:
通过这个接口,我们对onActivityStart回调方法里记录启动的次数 mActivityCount++,onActivityStop 回调里对 mActivityCount-- ,当mActivityCount == 1 时认为在前台,mActivityCount ==0 在后台。代码如下:
/** * 监听 前后台启动 * 自定义 可以很容易过滤一些不需要跳出手势密码的特殊的场景,比如 登录页 */ class GestureLifecycleHandler constructor(context:Context): Application.ActivityLifecycleCallbacks { companion object{ private const val TAG = "GestureLifecycleHandler" } private val uiScope = CoroutineScope(Dispatchers.Main) private var isOpenHandLock = false init { } /** * 记录 activity 前后台情况 */ private var mActivityCount: Int = 0 override fun onActivityPaused(activity: Activity?) { } override fun onActivityResumed(activity: Activity?) { } override fun onActivityStarted(activity: Activity?) { if(activityFilter(activity)){ return } mActivityCount ++ EasyLog.e(TAG,"onForeground = $mActivityCount") uiScope.launch { withContext(Dispatchers.IO){ isOpenHandLock = GestureManager.getAppGestureState() if(isOpenHandLock && mActivityCount == 1){ GestureActivity.actionStart(activity!!,GestureActivity.GestureState.Verify) } } } } override fun onActivityDestroyed(activity: Activity?) { } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { if(activityFilter(activity)){ return } mActivityCount-- EasyLog.e(TAG,"onBackground = $mActivityCount") } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { } private fun activityFilter(activity: Activity?):Boolean{ return activity is SplashActivity } }
以上就是 Android小视频app源码进入程序后启动手势密码的相关代码,更多内容欢迎关注之后的文章