0

我正在多台设备上启动 GPS 定位服务,该服务在 Android 版本 <= 7 的设备中正常工作,即使按下电源按钮并处于锁屏状态,但我尝试在带有 Android 8.0.0 的诺基亚 3 和按下电源按钮后服务停止,但一段时间后设备自行锁定时服务不会停止。当我按下电源按钮并解锁设备时,服务开始再次发送 GPS 数据。这是我的代码:

public class GPS_Service extends Service {
private static final String TAG = GPS_Service.class.getName();
private static final int minTimeSecondsSamplingRate = AppConfig.GPS_MIN_TIME;
private static final int minDistMetersSamplingRate = AppConfig.GPS_MIN_DISTANCE;

private LocationManager locationManager;
private LocationListener locationListener;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@SuppressLint("MissingPermission")
@Override
public void onCreate() {
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.d(TAG, "Location changed");
            Intent intentSendToMainActivity = new Intent(AppConfig.C_STR_INTENT_FILTER_LOCATION_CHANGED);
            intentSendToMainActivity.putExtra(AppConfig.C_STR_LATITUDE, location.getLatitude());
            intentSendToMainActivity.putExtra(AppConfig.C_STR_LONGITUDE, location.getLongitude());
            sendBroadcast(intentSendToMainActivity);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    };
    locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTimeSecondsSamplingRate, minDistMetersSamplingRate, locationListener);
        Log.i(TAG, "Starting Location Service");
    } else {
        Log.e(TAG, "Can't Start Location Service");
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (locationManager != null) {
        locationManager.removeUpdates(locationListener);
    }
}

}

我尝试为我的应用程序禁用电池优化,但问题仍然存在

4

1 回答 1

0

如果在 2 分钟内未收到任何位置,则停止/开始位置更新还创建一个服务并将其置于前台并将位置更新方法放入其中

一切顺利

于 2018-10-24T11:08:13.130 回答