[mobilesafe] 09_程序锁功能-看门狗原理

Android 4.0

程序锁功能-看门狗原理

看门狗原理:

步骤:
1、由于是一个不停的监视,所以需要一个后台服务,不停的监视当前打开的Activity
ActivityManager
2、由于是服务,所以需要一个配置来开启服务 Service(程序设置中配置)
3、获取到最新打开的Activity的packagename,然后和加锁应用的包名进行比较,如果在加锁应用的数据库中,那么跳出来一个Activity,让用户输入密码,才能进入加锁的应用中去,否则不给进
核心代码:
package cn.zengfansheng.mobilesafe.service;
 
import java.util.List;
 
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import cn.zengfansheng.mobilesafe.EnterPasswordActivity;
import cn.zengfansheng.mobilesafe.db.dao.AppLockDao;
 
/**
* 4、看门狗Service——监听应用程序的启动
* @author hacket
*/

public class WatchDogService extends Service {
 
    protected static final String TAG = "WatchDogService";
 
    private ActivityManager activityManager;
 
    private boolean flag;// 服务运行的标记,true表示运行,false表示停止
 
    private AppLockDao appLockDao;
 
    private Intent intent;
 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        // 1、获取ActivityManager管理者
        activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
 
        appLockDao = new AppLockDao(getApplicationContext());
        intent = new Intent(getApplicationContext(),
                EnterPasswordActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 外部开启Activity,一定要加上
 
        // 看门狗需要不停的监视后台正在运行的应用程序.
        new Thread() {
            public void run() {
                flag = true;
                while (flag) {
 
                    // 2、获取最近运行的3个Task
                    List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(3);
 
                    // 3、新打开的Activity在第一个task里面
                    RunningTaskInfo runningTaskInfo = runningTasks.get(0);
 
                    // 4、然后取栈顶,就是刚打开的Activity
                    ComponentName topActivity = runningTaskInfo.topActivity;
                    String packageName = topActivity.getPackageName();
 
                    boolean isLock = appLockDao.find(packageName);
                    if (isLock) {// 如果锁上了,进入输入密码Activity界面
                        Log.i(TAG, packageName+"锁上了~");
                        startActivity(intent);
                    } else {// 没有锁上
                        Log.i(TAG, packageName + "没有锁上~");
                    }
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(packageName);
                }
            }
        }.start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        flag = false;
    }
}
权限:
 <uses-permission android:name="android.permission.GET_TASKS" />