Reputation: 582
I have a service that needs to check if a certain application is in the foreground. When the application exits the foreground, the service will run a command. Right now, I have this implemented with a timer:
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;
}
Which is great, it works as intended. But it's eating up an enormous amount of CPU time, and the UI for all applications, even the launcher, is jumpy. Is there a better method of doing this?
Upvotes: 1
Views: 64
Reputation: 3430
probably mgr.getRunningTasks(showLimit); is taking lot of resources..you can reduce "showLimit" value and check the difference.
You can also try calling http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/com/android/internal/app/IUsageStats.java through reflection if you planning to build app usage manager kind of app...
Upvotes: 2