我有一项服务需要检查某个应用程序是否在前台。当应用程序退出前台时,该服务将运行命令。现在,我用计时器实现了这个:
public int onStartCommand(Intent intent, int startid) {
handler = new Handler();
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(MyService.this, "Service has started.", Toast.LENGTH_LONG);
toast.show();
}
});
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run()
{
/* Get all Tasks available (with limit set). */
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> allTasks = mgr.getRunningTasks(showLimit);
/* Loop through all tasks returned. */
for (ActivityManager.RunningTaskInfo aTask : allTasks)
{
Log.i("MyApp", "Task: " + aTask.baseActivity.getClassName());
if (aTask.baseActivity.getClassName().equals("package")) {
running=true;
}
else {
RunAsRoot(commandsdefault);
}
}
}
}, 6000, 3000); // every 3 seconds, with a 6 second first execution delay
return START_STICKY;
}
哪个好,它按预期工作。但是它占用了大量的CPU时间,所有应用程序的UI,甚至是启动器都是如此。有没有更好的方法呢?
答案 0 :(得分:2)
可能是mgr.getRunningTasks(showLimit);需要大量资源..你可以减少&#34; showLimit&#34;价值并检查差异。
如果您计划构建应用使用管理器类型的应用,也可以尝试通过反映调用http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/com/android/internal/app/IUsageStats.java ...