N
N
newdancer2018-11-28 22:30:53
Android
newdancer, 2018-11-28 22:30:53

How to fix background service on Android 8?

How to fix background service on Android 8?
Registered in the manifest

<service
            android:name="com.test.test.services.LocationService"
            android:exported="true"
            android:process=":LocationService" />

call the service like this
if (status) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(this, LocationService.class));
            } else {
                startService(new Intent(this, LocationService.class));
            }

the service itself
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";
        }
    }
}

The service should always work both foregraund and background. As a result, the service starts and ends after a while. What's wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Varakosov, 2018-11-29
@thelongrunsmoke

Everything is good. From the 26th API, the GPS in the service receives updates no more than a few times per hour, we read the docs .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question