创建程序锁服务, 在服务中开启看门狗, 当服务销毁时关闭看门狗功能
---------------------------------------------------------------------------------------------------------------------------
关心用户正在打开的应用需要添加权限:
<
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
;
};
}