android 判断服务与APP是否运行中
可封装成方法,可直接使用
/**
* Judge a service is run or not.
* @param context Current application context.
* @param className The service class name.
* @return Return true if service is running, false or not.
*/
public static boolean isServiceRun(Context context, String className) {
boolean isRun = false;
final int maxNum = 100;
if (context == null || className == null) {
LogHelper.e(TAG, "isServiceRun mContext = " + context + " className = " + className);
return false;
}
try {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(maxNum);
int size = serviceList.size();
for (int i = 0; i < size; i++) {
if (serviceList.get(i).service.getClassName().equals(className)) {
isRun = true;
break;
}
}
} catch (Exception ex) {
LogHelper.e(TAG, "isServiceRun " + ex);
}
LogHelper.d(TAG, "isServiceRun service name = " + className + " is run " + isRun);
return isRun;
}判断APP当前是否前台进程
private static boolean isForegroundApp(Context context, String pkgName) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
return !tasks.isEmpty() && pkgName.equals(tasks.get(0).topActivity.getPackageName());
}版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。




评论