diff --git a/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainActivity.java b/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainActivity.java index f452860..9026924 100644 --- a/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainActivity.java +++ b/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainActivity.java @@ -1,5 +1,6 @@ package cc.winboll.studio.gpsrelaysentinel; +import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; @@ -88,6 +89,11 @@ public class MainActivity extends AppCompatActivity { } private void stopService() { + // 先设置SP标记为不启用 + MainActivity.this.getSharedPreferences(MainService.PREF_NAME, Context.MODE_PRIVATE) + .edit() + .putBoolean(MainService.KEY_SERVICE_ENABLED, false) + .apply(); Intent intent = new Intent(MainActivity.this, MainService.class); stopService(intent); ToastUtils.show("GPS Service stopped"); diff --git a/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainService.java b/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainService.java index 6de85b6..8e3ec41 100644 --- a/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainService.java +++ b/gpsrelaysentinel/src/main/java/cc/winboll/studio/gpsrelaysentinel/MainService.java @@ -26,6 +26,8 @@ public class MainService extends Service { private NotificationCompat.Builder mNotificationBuilder; private static final String CHANNEL_ID = "gps_relay_channel"; private static final int NOTIFICATION_ID = 1; + private static final String PREF_NAME = "gps_relay_service_prefs"; + private static final String KEY_SERVICE_ENABLED = "service_enabled"; @Override public void onCreate() { @@ -33,15 +35,29 @@ public class MainService extends Service { LogUtils.d(TAG, "Service onCreate"); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); createNotificationChannel(); + if (isServiceEnabled()) { + LogUtils.d(TAG, "Service was enabled, starting GPS updates"); + run(); + } } @Override public int onStartCommand(Intent intent, int flags, int startId) { LogUtils.d(TAG, "Service onStartCommand"); + setServiceEnabled(true); run(); return START_STICKY; } + private boolean isServiceEnabled() { + return getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).getBoolean(KEY_SERVICE_ENABLED, false); + } + + 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 run() { if (mIsRunning) { LogUtils.d(TAG, "GPS updates already running");