6.7 看门狗原理

创建程序锁服务,  在服务中开启看门狗, 当服务销毁时关闭看门狗功能

 

 

---------------------------------------------------------------------------------------------------------------------------

关心用户正在打开的应用需要添加权限:

     < uses-permission   android:name =   "android.permission.GET_TASKS"   />




-----------------------



public   class   WatchDogService   extends   Service {

       protected   static   final   String   TAG   =   "WatchDogService" ;
       private   ActivityManager    am ;
       private   boolean   flags ;
       private   AppLockDao   dao ;
      
       @Override
       public   IBinder onBind(Intent intent) {
            
               return   null ;
      }
      
       /**
       * 服务开启时
       */
       @Override
       public   void   onCreate() {
            Log. i( TAG ,   "开启服务"   );
            
               dao =   new   AppLockDao(getApplicationContext()); 
            
               //1.创建activity管理员
               am =(ActivityManager) getSystemService(   ACTIVITY_SERVICE );
            
               //2.看门狗在服务开启时不停的监视着后台正在运行的程序
               new   Thread(){
                     public   void   run() {
                           flags =   true ;
                        
                           while (   flags ){       //获取正在运行的任务栈     3:可以任意定义,表示近期开启的3个任务栈
                        List<RunningTaskInfo> runningTasks =   am .getRunningTasks(3);
                        
                           //最上层的任务栈:   刚打开的应用程序的任务栈
                        RunningTaskInfo runningTaskInfo = runningTasks.get(0);
                        
                           //得到刚刚开启的应用程序的activity的名称
                        String packageName = runningTaskInfo. topActivity .getPackageName();
                        
                           //判断得到的包名的应用是否在已加锁的数据库中
                           if (   dao .find(packageName)){
                              Log. i( TAG ,   "弹出提示输入密码的activity"   );
                              Intent intent=   new   Intent(getApplicationContext(),WatchDogActivity. class   );
                              intent.setFlags(Intent.   FLAG_ACTIVITY_NEW_TASK );   //开启新任务栈
                              startActivity(intent);
                        }
                        
                        
                        
                        }
                  };
                  
      }.start();
            
            
            
            
            
               super .onCreate();
      }
      
      
       /**
       * 服务销毁时
       */
       public   void   onDestroy() {
            Log. i( TAG ,   "关闭服务..."   );
               flags =   false ;
            
            
      };
      

}



 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值