feat(gpsrelaysentinel): 使用SP标记管理服务状态并支持自启动
- onStartCommand返回START_STICKY实现服务自启动 - onStartCommand直接设置SP标记为启用,不检查现有标记 - onCreate时检查SP标记,已启用则自动启动GPS - onDestroy不再改变SP标记 - MainActivity stopService前先设置SP标记为不启用
This commit is contained in:
@@ -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");
|
||||
|
||||
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user