GVillani82
GVillani82

Reputation: 17429

Android: test from a service, if an Activity is running.

I have a service that runs in background. I I wish it could perform an action, only if a certain activity is running. How can I test, from a service, if the activity is running?

Upvotes: 2

Views: 357

Answers (3)

Sahil Mahajan Mj
Sahil Mahajan Mj

Reputation: 11141

Use the below method with your package name.It will return true if any of your activity is in foreground.

public boolean isForeground(String myPackage){
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
 List< ActivityManager.RunningTaskInfo > runningTaskInfo = am.getRunningTasks(1); 

     ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
   if(componentInfo.getPackageName().equals(myPackage)) return true;
return false;
}

Upvotes: 0

nicopico
nicopico

Reputation: 3636

Maybe you can do it the other way around, sending intent from your activity to the service.

For example, you can send an intent on the activity onResume, telling your service the activity is live, and another on onPause, telling the service the activity has stopped

Upvotes: 0

DroidBender
DroidBender

Reputation: 7892

You can use the Package Manager and the Activity Manager:

PackageManager: Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through getPackageManager().

ActivityManager: Interact with the overall activities running in the system.

But, a more simple approach would be: When starting your Activity (onCreate/onResume), send a message with service.send(..) or an Intent with service.onStartCommand(..) so the service knows that your particular Activity has been started.

Upvotes: 2

Related Questions