Как исправить работу сервиса в background на Android 8?
Прописал в манифесте
<service
android:name="com.test.test.services.LocationService"
android:exported="true"
android:process=":LocationService" />
вызываю сервис так
if (status) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, LocationService.class));
} else {
startService(new Intent(this, LocationService.class));
}
сам сервис
public class LocationService extends Service {
private static final int LOCATION_INTERVAL = 30000;
private static final float LOCATION_DISTANCE = 0;
private static String url = "тут урл";
private final Context mContext;
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
private LocationManager mLocationManager = null;
private double latitude, longitude;
private JSONParser jsonParser = new JSONParser();
private String userId = "";
public LocationService() {
super();
mContext = LocationService.this;
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("TEST", "Service started");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
userId = String.valueOf(Prefs.loadInt(mContext, Prefs.PREFS_USER_ID));
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i("TEST", "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d("TEST", "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i("TEST", "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d("TEST", "gps provider does not exist " + ex.getMessage());
}
}
@Override
public void onDestroy() {
Log.i("TEST", "LocationService onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i("TEST", "fail to remove location listners, ignore", ex);
}
}
}
}
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.w("TEST", "latlong=" + latitude + " " + longitude + " userId=" + userId);
mLastLocation.set(location);
new SendToServer().execute(String.valueOf(latitude), String.valueOf(longitude), userId);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class SendToServer extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... latlong) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("status", String.valueOf(DriverStatus.INTRANSIT));
params.put("latitude", latlong[0]);
params.put("longitude", latlong[1]);
String url = url + latlong[2];
Log.d("TEST", "Create Response: " + url);
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
} catch (Exception e) {
Log.i("TEST", "location send error=" + e.toString());
}
return "call";
}
}
}
Сервис должен работать всегда и foregraund и в background. В итоге сервис запускается и через некоторое время завершается. Что не так?