Search code examples
javaandroidandroid-serviceandroid-gpslocation-services

How to save location data in array in service and send that array to activity/fragment? [Android/Java]


I'm creating an Android program with Java and I need to get location every 5s (and I already did it using LocationServices and FusedLocationProviderClient). Everything works fine -> I mean logs are created and location is updating. Now I need to save that data (instead of showing it in logger) to an array like this:

PSEUDOCODE:
array[0][0] = lat1,
array[0][1] = lng1,
array[1][0] = lat2,
array[1][1] = lng2 ... etc...

and send that array to an Activity/Fragment where I started service. How to do it? I want to pass the data continuously or after service ends. Help me please

I have created LocationService which is implementing Service like this:

@Override
public void onCreate() {
    super.onCreate();
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    locationCallback = new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            Log.d("LOCALIZATOR_LOG", "Lat: " + locationResult.getLastLocation().getLatitude() + ", Lng: " + locationResult.getLastLocation().getLongitude());
        }
    };
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    requestLocation();
    return super.onStartCommand(intent, flags, startId);
}

private void requestLocation() {
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}

and in my Activity I use that service like this:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    if(Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            startLocService();
        }
    } else {
        startLocService();
    }
}

void startLocService() {
    Intent intent = new Intent(TestActivity.this, LocationService.class);
    startService(intent);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch(requestCode){
        case 1:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){

            } else {
                Toast.makeText(this, "I need a permission", Toast.LENGTH_LONG).show();
            }
    }
}

Solution

  • You can use a LocalBroadcastManager to pass the data via bundle in Intent from Service

    public void onLocationResult(LocationResult locationResult) {
         super.onLocationResult(locationResult);
         Log.d("LOCALIZATOR_LOG", "Lat: " + locationResult.getLastLocation().getLatitude() + ", Lng: " + locationResult.getLastLocation().getLongitude());
         Intent intent = new Intent("LatLongUpdate");
         intent.putExtra("Latitude", locationResult.getLastLocation().getLatitude());
         intent.putExtra("Longitude", locationResult.getLastLocation().getLongitude());
         LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }
    

    And then in Activity

    private ArrayList<ArrayList<Long>> locations = new ArrayList<>();
    private BroadcastReceiver locationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Long latitude = intent.getLongExtra("Latitude");
            Long longitude = intent.getLongExtra("Longitude");
            //save to array in activity
            ArrayList<Long> loc = new ArrayList<>();
            loc.add(latitude);
            loc.add(longitude);
            locations.add(loc)
        }
    };
    LocalBroadcastManager.getInstance(this).registerReceiver(
                locationReceiver, new IntentFilter("LatLongUpdate"));