package com.dayu.pipirrapp.utils;
|
|
import android.app.ActivityManager;
|
import android.content.Context;
|
import android.content.Intent;
|
import android.os.Build;
|
|
import com.dayu.pipirrapp.service.MyLocationService;
|
|
/**
|
* ServiceUtils - 服务相关的公共方法
|
*
|
* @author zuoxiao
|
* @version 1.0
|
* @since 2024-12-12
|
*/
|
public class ServiceUtils {
|
|
/**
|
* 判断当前服务是否已经启动
|
*
|
* @param context
|
* @param serviceClass
|
* @return
|
*/
|
public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
|
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
|
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
|
if (serviceClass.getName().equals(service.service.getClassName())) {
|
return true;
|
}
|
}
|
return false;
|
}
|
|
|
/**
|
* 开启定位服务
|
*
|
* @param context
|
* @param isSingle
|
*/
|
public static void startLocationService(Context context, boolean isSingle) {
|
if (!isServiceRunning(context, MyLocationService.class)) {
|
Intent location = new Intent(context, MyLocationService.class);
|
location.putExtra("isSingle", isSingle);
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
context.startForegroundService(location);
|
} else {
|
context.startService(location);
|
}
|
}
|
}
|
|
/**
|
* 关闭定位服务
|
*
|
* @param context
|
*/
|
public static void stopLocationService(Context context) {
|
try {
|
Intent location = new Intent(context, MyLocationService.class);
|
context.stopService(location);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
}
|