I'm trying to create a service that will continuously check the foreground application, and when the certain app comes in to the foreground, do a task. When it exits the foreground, do another task. This should occur repeatedly until the user stops the service (I have service handling done already).
I don't know how to go about this. Here is how I'm checking for the current foreground application:
/* 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;
}
Then, I have a simple if/else that checks the status of running and preforms the tasks as required:
if(running =! true) {
MainActivity defaults = new MainActivity();
defaults.RunAsRoot(commandsdefault);
}
else {
MainActivity defaults = new MainActivity();
defaults.RunAsRoot(commands);
}
Now, that doesn't run continuously, it just does it once and stops. So, I put the entirety of my onCreate()
inside a while()
:
boolean justrun = true;
while(doit = true) {
//everything here: foreground checker, along with if/else
}
That didn't work either: Everything was just super slow and it ended up force closing, I'm assuming because it ate up all the resources it could.
How do I go about doing this? Main main goal seems to be pretty straightforward... I just want to get the foreground application package name, and just do commands as it changes.
EDIT: I added the following method to MyService:
public int serviceservice() {
boolean running = true;
int showLimit = 20;
boolean doit = true;
/* 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;
}
if(running =! true) {
MainActivity defaults = new MainActivity();
defaults.RunAsRoot(commandsdefault);
}
return START_STICKY;
}
And I called serviceservice(); in my OnCreate() and onStart(). It still only runs once. :/