refactor(gpsrelaysentinel): 重构MainService添加run函数管理GPS监听
- 将GPS定位申请逻辑从onCreate()转移到新增的run()函数 - onStartCommand()调用run()启动GPS监听 - 添加mIsRunning标志防止重复启动 - onCreate()不再直接初始化定位功能 - onDestroy()中重置mIsRunning标志
This commit is contained in:
@@ -15,21 +15,26 @@ public class MainService extends Service {
|
||||
public static final String TAG = "MainService";
|
||||
private LocationManager mLocationManager;
|
||||
private LocationListener mLocationListener;
|
||||
private boolean mIsRunning = false;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
LogUtils.d(TAG, "Service onCreate");
|
||||
initLocation();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
LogUtils.d(TAG, "Service onStartCommand");
|
||||
run();
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
private void initLocation() {
|
||||
private void run() {
|
||||
if (mIsRunning) {
|
||||
LogUtils.d(TAG, "GPS updates already running");
|
||||
return;
|
||||
}
|
||||
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
|
||||
mLocationListener = new LocationListener() {
|
||||
@Override
|
||||
@@ -62,6 +67,7 @@ public class MainService extends Service {
|
||||
mLocationListener
|
||||
);
|
||||
LogUtils.d(TAG, "GPS location updates requested");
|
||||
mIsRunning = true;
|
||||
}
|
||||
} catch (SecurityException e) {
|
||||
LogUtils.e(TAG, "Permission denied: " + e.getMessage());
|
||||
@@ -83,6 +89,7 @@ public class MainService extends Service {
|
||||
LogUtils.e(TAG, "Permission denied when removing updates: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
mIsRunning = false;
|
||||
LogUtils.d(TAG, "Service onDestroy");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user