import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
/**
* 看门狗服务
* @author Administrator
*
*/
public class WatchDogService extends Service {
private boolean isWatch;//是否监控
private ActivityManager am;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
watchDog();//看门狗的逻辑
super.onCreate();
}
private void watchDog(){
new Thread(){
public void run() {
isWatch = true;
while (isWatch) {
//通过isWatch 来控制该线程
//时刻监控任务栈
List runningTasks = am.getRunningTasks(1);//获取最新的任务栈集合
RunningTaskInfo runningTaskInfo = runningTasks.get(0);//最新打开的任务栈(不管多少个栈,只看第一个)
//任务栈中获取顶部activity
String packName = runningTaskInfo.topActivity.getPackageName();
System.out.println(packName);
SystemClock.sleep(50);//每个50毫秒 狗监控任务栈
}
};
}.start();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
isWatch = false;
super.onDestroy();
}
}
清单文件中注册服务:
<service android:name="com.lqr.service.WatchDogService">service>