JohnnyLambada
JohnnyLambada

Reputation: 12826

Detect service availability from Activity's onCreate

From within the onCreate within an Activity, I'd like to be able to detect whether a Service in a different application (that I'm also writing) is available and running. The problem with AIDL is that there is no synchronous option. I'd like my activity to actually wait to see if the Service is available and act accordingly if it is not.

The best answer I've come up with is for the service to open a TCP socket and for the Activity to try to connect to it. If that succeeds, then the Activity's onCreate will know that the service is available. However this is a kludge at best.

So, bottom line: how can my Activity's onCreate synchronously check to see if an external Service is available and take action before returning from the onCreate routine?

Upvotes: 1

Views: 636

Answers (1)

Aleadam
Aleadam

Reputation: 40391

You can loop through the List returned by public List<ActivityManager.RunningServiceInfo> getRunningServices (int maxNum). Each ActivityManager.RunningServiceInfo contains the information you need

Check the API here and here

ActivityMAnager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<ActivityManager.RunningServiceInfo> rsiList = am.getRunningServices (999);
boolean found = null;
for (ActivityManager.RunningServiceInfo rsi: rsiList) {
    if (rsi.service.getPackageName().equals("MYPACKAGE") {
       found = true;
       break;
    }
}
if (found) {
    // do whatever
} else {
    // alternative
}

Upvotes: 3

Related Questions