Android Background Location Service not Uploading Coordinates to Server and Getting Killed

44 views Asked by At

Title: Android Background Location Service not Uploading Coordinates to Server and Getting Killed

Description: I am currently working on an Android application in Java that involves a background location service. The goal is to periodically obtain the device's location and upload the latitude and longitude coordinates to a server. I have implemented a service named LocationService and granted all the necessary permissions in the manifest file as follows:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

<service
    android:foregroundServiceType="location"
    android:name=".LocationService"
    android:enabled="true"
    android:exported="false"
    tools:ignore="ForegroundServicePermission" />

In the LocationService, I am using FusedLocationProviderClient to access the device's location. However, after some time, the service stops uploading location coordinates to the server, and the service itself gets killed.

I have already ensured that the necessary permissions are granted, and the service is declared in the manifest with the appropriate configurations. Despite this, the background service is not functioning as expected.

I suspect there might be issues related to the Android system's battery optimizations or restrictions on background services. I have also considered potential issues with the lifecycle of the service or the handling of location updates.

Could anyone provide insights or solutions on how to address this problem? I am open to suggestions regarding improvements to my code or any additional configurations needed to ensure the continuous functioning of the background location service.

Here is full code of my service:



public class LocationService extends Service {


    static protected LocationRequest locationRequest;

    static FusedLocationProviderClient mFusedLocationProviderClient = null;
    static LocationCallback mLocationCallback;

    static boolean GPS_SIGNAL_STATUS = false;
    static String LOCATION_PERMISSION_STATUS = "true";


    static double current_lat, current_lng;


    Notification notification;

    NotificationManager notificationManager = null;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d("GPS_SIGNAL", "inside onCreate()...of service..");

        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(5000);
        locationRequest.setFastestInterval(20000);

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationAvailability(@NonNull LocationAvailability locationAvailability) {
                super.onLocationAvailability(locationAvailability);


            }

            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                super.onLocationResult(locationResult);

                int index = locationResult.getLocations().size() - 1;
                current_lat = locationResult.getLocations().get(index).getLatitude();
                current_lng = locationResult.getLocations().get(index).getLongitude();

                Log.d("GPS_SIGNAL", "current lat : "+current_lat+" current lng : "+current_lng);

                RequestHelper.uploadLiveGpsData(MainActivity.orangecircle, current_lat, current_lng);

                startForeground(NOTIFICATION_ID, getNotification());


            }
        };

            Log.e("GPS_SIGNAL", "inside if build version in onCreate of Service....");

        NotificationChannel channel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channel = new NotificationChannel(CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_HIGH);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager = (NotificationManager)   this.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        createLocationRequest();
        return START_STICKY;
    }

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


    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.e("GPS_SIGNAL", "inside onDestroy()...");
        removeLocationUpdates();

    }


    String CHANNEL_ID = "12345";
    int NOTIFICATION_ID = 12345;

    Notification getNotification() {

        Log.d("GPS_SIGNAL", "inside getNotification()....");

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Location Updates")
                .setContentText("latitude  : " + current_lat + " longitude : " + current_lng)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setChannelId(CHANNEL_ID)
                .setOngoing(true).build();

        return notification;
    }



    void createLocationRequest() {
        try {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            Log.d("GPS_SIGNAL", "inside createLocationRequest().....");


            mFusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, null);

        }catch (Exception e){
            Log.e("GPS_SIGNAL", "error inside createLocationRequest() : "+e.getMessage());
            e.printStackTrace();
        }

    }


    private void removeLocationUpdates(){
        if(mFusedLocationProviderClient != null){
            mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
            mFusedLocationProviderClient = null;
        }

        stopForeground(true);
        stopSelf();
    }





}

One more thing, I am not getting any notification when I put my in the background. I don't know why.

Also, I am starting my service my MainActivity like this:

Intent intentService;

intentService = new Intent(this, LocationService.class);

this.startService(intentService);

Thank you in advance for your assistance!

Tackled Android background location service issues with optimizations. Seeking community insights for continuous background service functioning.

0

There are 0 answers