改进应用主要服务启动类

This commit is contained in:
2026-05-07 14:38:56 +08:00
parent e24c9bdce3
commit ceeacb5022

View File

@@ -12,154 +12,236 @@ import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libgpsrelaysentinel.manager.GpsSubscribeManager;
import cc.winboll.studio.libgpsrelaysentinel.manager.SubscribeLocationManager;
import cc.winboll.studio.libgpsrelaysentinel.model.GpsSubscribeMsg;
import java.util.Map;
public class MainService extends Service {
/**
* WinBoLL Studio
* GPS定位核心前台服务
* 负责GPS持续监听、订阅者步长判断、基准坐标刷新、前台常驻通知
* Java7 | API26~30
* 新增实时同步最新GPS到MainActivity静态坐标
*/
public final class MainService extends Service {
//日志标签
public static final String TAG = "MainService";
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private boolean mIsRunning = false;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationBuilder;
//前台通知常量
private static final String CHANNEL_ID = "gps_relay_channel";
private static final int NOTIFICATION_ID = 1;
//SP配置常量
static final String PREF_NAME = "gps_relay_service_prefs";
static final String KEY_SERVICE_ENABLED = "service_enabled";
private int mGpsCount = 0;
//系统定位 & 通知控件
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationBuilder;
//运行状态 & 计数
private boolean mIsRunning = false;
private int mGpsLocationCount = 0;
//订阅管理器
private GpsSubscribeManager mSubscribeManager;
private SubscribeLocationManager mLocationRuleManager;
@Override
public void onCreate() {
super.onCreate();
LogUtils.d(TAG, "Service onCreate");
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
createNotificationChannel();
if (isServiceEnabled()) {
LogUtils.d(TAG, "Service was enabled, starting GPS updates");
run();
initManager();
initNotificationConfig();
//上次开启状态则自动重启GPS监听
if (checkServiceEnableStatus()) {
LogUtils.d(TAG, "历史服务已启用自动启动GPS监听");
startGpsLocationListen();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LogUtils.d(TAG, "Service onStartCommand");
setServiceEnabled(true);
run();
saveServiceEnableStatus(true);
startGpsLocationListen();
return START_STICKY;
}
private boolean isServiceEnabled() {
return getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).getBoolean(KEY_SERVICE_ENABLED, false);
/**
* 初始化订阅规则管理器
*/
private void initManager() {
mSubscribeManager = GpsSubscribeManager.getInstance();
mLocationRuleManager = SubscribeLocationManager.getInstance();
}
private void setServiceEnabled(boolean enabled) {
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).edit().putBoolean(KEY_SERVICE_ENABLED, enabled).apply();
LogUtils.d(TAG, "Service enabled set to: " + enabled);
/**
* 初始化通知渠道与管理类
*/
private void initNotificationConfig() {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
createSystemNotificationChannel();
}
private void run() {
/**
* 读取服务启用状态
*/
private boolean checkServiceEnableStatus() {
return getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.getBoolean(KEY_SERVICE_ENABLED, false);
}
/**
* 保存服务启用状态
*/
private void saveServiceEnableStatus(boolean enabled) {
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
.edit()
.putBoolean(KEY_SERVICE_ENABLED, enabled)
.apply();
LogUtils.d(TAG, "服务启用状态已设置:" + enabled);
}
/**
* 启动GPS定位监听核心逻辑
*/
private void startGpsLocationListen() {
if (mIsRunning) {
LogUtils.d(TAG, "GPS updates already running");
LogUtils.d(TAG, "GPS监听已正在运行,无需重复启动");
return;
}
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
initLocationListener();
try {
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//定位间隔1000毫秒 / 最小位移1米
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
1,
mLocationListener
);
mIsRunning = true;
startServiceForegroundNotification();
LogUtils.d(TAG, "GPS定位监听已成功注册");
}
} catch (SecurityException e) {
LogUtils.e(TAG, "定位权限缺失,监听启动失败:" + e.getMessage());
}
}
/**
* 初始化定位监听回调
*/
private void initLocationListener() {
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
mGpsCount++;
String gpsInfo = "Lat: " + location.getLatitude() + ", Lng: " + location.getLongitude();
LogUtils.d(TAG, "Location changed: " + gpsInfo);
updateNotification(gpsInfo);
//管理器初始化
GpsSubscribeManager subscribeManager = GpsSubscribeManager.getInstance();
SubscribeLocationManager locationManager = SubscribeLocationManager.getInstance();
//遍历所有订阅者做距离判断+定点更新
Map<String, GpsSubscribeMsg> subscribeMap = subscribeManager.getSubscribeMap();
for (Map.Entry<String, GpsSubscribeMsg> entry : subscribeMap.entrySet()) {
String sid = entry.getKey();
GpsSubscribeMsg subscribeMsg = entry.getValue();
double nowLat = location.getLatitude();
double nowLng = location.getLongitude();
//判断是否满足推送
boolean canPush = locationManager.isNeedPush(sid, nowLat, nowLng);
if (canPush) {
//执行发送GPS广播
//sendGpsBroadcast(...);
//推送成功立刻刷新订阅者基准坐标
locationManager.updateSubscriberPoint(sid, nowLat, nowLng);
}
}
handleLocationUpdate(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
LogUtils.d(TAG, "Status changed: " + provider + ", status: " + status);
LogUtils.d(TAG, "GPS状态变更 -> 提供者:" + provider + " 状态:" + status);
}
@Override
public void onProviderEnabled(String provider) {
LogUtils.d(TAG, "Provider enabled: " + provider);
LogUtils.d(TAG, "GPS提供者已启用" + provider);
}
@Override
public void onProviderDisabled(String provider) {
LogUtils.d(TAG, "Provider disabled: " + provider);
LogUtils.d(TAG, "GPS提供者已禁用" + provider);
}
};
}
try {
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
1,
mLocationListener
);
LogUtils.d(TAG, "GPS location updates requested");
mIsRunning = true;
startForegroundNotification();
/**
* 处理每次定位刷新|核心:步长判断 + 基准坐标更新
* 新增同步最新坐标到MainActivity静态变量
*/
private void handleLocationUpdate(Location location) {
mGpsLocationCount ++;
String locationInfo = "纬度:" + location.getLatitude() + " , 经度:" + location.getLongitude();
LogUtils.d(TAG, "定位刷新 -> " + locationInfo);
//========== 新增关键代码实时同步最新真实GPS坐标 ==========
MainActivity.lastLat = location.getLatitude();
MainActivity.lastLng = location.getLongitude();
//==========================================================
//更新前台通知文案
updateForegroundNotification(locationInfo);
//遍历全部订阅者进行推送规则判断
Map<String, GpsSubscribeMsg> subscribeAllMap = mSubscribeManager.getSubscribeMap();
for (Map.Entry<String, GpsSubscribeMsg> entry : subscribeAllMap.entrySet()) {
final String subscribeSid = entry.getKey();
final GpsSubscribeMsg subscribeConfig = entry.getValue();
double currentLat = location.getLatitude();
double currentLng = location.getLongitude();
//判断是否满足推送条件(全订阅/步长阈值)
boolean allowPush = mLocationRuleManager.isNeedPush(subscribeSid, currentLat, currentLng);
if (allowPush) {
//推送成功后刷新该订阅者基准定点坐标
mLocationRuleManager.updateSubscriberPoint(subscribeSid, currentLat, currentLng);
}
} catch (SecurityException e) {
LogUtils.e(TAG, "Permission denied: " + e.getMessage());
}
}
private void createNotificationChannel() {
/**
* 创建系统通知渠道
*/
private void createSystemNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"GPS Relay Service",
NotificationManager.IMPORTANCE_LOW
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID,
"GPS Relay Service",
NotificationManager.IMPORTANCE_LOW
);
channel.setDescription("GPS Relay Sentinel service channel");
mNotificationManager.createNotificationChannel(channel);
notificationChannel.setDescription("GPSRelaySentinel 后台常驻服务通知");
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
private void startForegroundNotification() {
/**
* 开启前台常驻通知
*/
private void startServiceForegroundNotification() {
mNotificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("GPS Relay Service")
.setContentText("Waiting for GPS data...")
.setSmallIcon(android.R.drawable.ic_menu_mylocation)
.setOngoing(true);
.setContentTitle("GPS 中继服务")
.setContentText("等待GPS定位数据...")
.setSmallIcon(android.R.drawable.ic_menu_mylocation)
.setOngoing(true);
Notification notification = mNotificationBuilder.build();
startForeground(NOTIFICATION_ID, notification);
}
private void updateNotification(String gpsInfo) {
/**
* 动态更新通知内容
*/
private void updateForegroundNotification(String locationText) {
if (mNotificationBuilder != null) {
mNotificationBuilder.setContentText(gpsInfo + " | Count: " + mGpsCount);
mNotificationBuilder.setContentText(locationText + " | 定位次数:" + mGpsLocationCount);
mNotificationManager.notify(NOTIFICATION_ID, mNotificationBuilder.build());
}
}
@@ -172,14 +254,16 @@ public class MainService extends Service {
@Override
public void onDestroy() {
super.onDestroy();
//注销定位监听
if (mLocationManager != null && mLocationListener != null) {
try {
mLocationManager.removeUpdates(mLocationListener);
} catch (SecurityException e) {
LogUtils.e(TAG, "Permission denied when removing updates: " + e.getMessage());
LogUtils.e(TAG, "移除定位监听权限异常:" + e.getMessage());
}
}
mIsRunning = false;
LogUtils.d(TAG, "Service onDestroy");
LogUtils.d(TAG, "MainService 已销毁GPS监听已停止");
}
}