开发者

Detect service availability from Activity's onCreate

开发者 https://www.devze.com 2023-02-25 07:08 出处:网络
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 tha

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 se开发者_JAVA百科e if an external Service is available and take action before returning from the onCreate routine?


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号