-
Notifications
You must be signed in to change notification settings - Fork 11
Open
Description
来源:http://www.wangchenlong.org/2016/05/18/tips/1605/181-android-tips-8/
服务检测比较具有迷惑性, 不能直接通过类名检查, 一定要判断UID是否相同, 否则多个应用使用相同的服务, 会出现检查错误, 有一个启动就会成功. 添加UID检查, 才可以正确使用.
用于在重启动服务时, 进行服务保活, 防止重复启动.
/**
* 判断服务是否启动, 注意只要名称相同, 会检测任何服务.
*
* @param context 上下文
* @param serviceClass 服务类
* @return 是否启动服务
*/
public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
if (context == null) {
return false;
}
Context appContext = context.getApplicationContext();
ActivityManager manager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
if (manager != null) {
List<ActivityManager.RunningServiceInfo> infos = manager.getRunningServices(Integer.MAX_VALUE);
if (infos != null && !infos.isEmpty()) {
for (ActivityManager.RunningServiceInfo service : infos) {
// 添加Uid验证, 防止服务重名, 当前服务无法启动
if (getUid(context) == service.uid) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
}
}
}
return false;
}
/**
* 获取应用的Uid, 用于验证服务是否启动
*
* @param context 上下文
* @return uid
*/
public static int getUid(Context context) {
if (context == null) {
return -1;
}
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (manager != null) {
List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
if (infos != null && !infos.isEmpty()) {
for (ActivityManager.RunningAppProcessInfo processInfo : infos) {
if (processInfo.pid == pid) {
return processInfo.uid;
}
}
}
}
return -1;
}
Metadata
Metadata
Assignees
Labels
No labels