管灌系统巡查员智能手机App
zuoxiao
2025-01-08 94c235c116ebca594662417b5fb2c7378f326c6b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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();
        }
    }
 
}