Nafsika
Nafsika

Reputation: 47

Find Current Location using Background Service on Android studio in java

I want to get the current location and show it on my maps activity. I have succeeded doing that but I have to move the part of the code that I use to find the current location to a background service and nothing will work from what I have tried. This is the code I used before to find the current location and it worked:

 public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

private LocationManager manager;

private LocationListener listener;

private static final int LOCATION_PERMISSIONS_REQUEST_CODE = 3;

private MyService myService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = ActivityMapsBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
   

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.GoogleMap);
    mapFragment.getMapAsync(this);


    manager = (LocationManager) getSystemService(LOCATION_SERVICE);
    listener = new LocationListener() {
        @Override
        public void onLocationChanged(@NonNull Location location) {
            if(mMap!=null) {
                LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.addMarker(new MarkerOptions().position(currentLocation));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));

            }

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

    };
    getLocation();

    //initialize start and cancel button
    findViewById(R.id.startButton).setOnClickListener(view -> {
        
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), MyService.class);
        //startService(intent);
       

    });

    findViewById(R.id.cancelButton).setOnClickListener(view -> {
       
        Intent serviceIntent = new Intent(this, MyService.class);
        //stopService(serviceIntent);

        //return back to main activity
        Intent mainActivity = new Intent(this, MainActivity.class);
        startActivity(mainActivity);
    });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode==LOCATION_PERMISSIONS_REQUEST_CODE) {
        int count =0;
        for(String permission: permissions) {
            if(permission==android.Manifest.permission.ACCESS_FINE_LOCATION){
                if(grantResults[count]==PackageManager.PERMISSION_GRANTED){
                    getLocation();
                }
            }
            count++;
        }
    }
}



private void getLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 50, listener);
    } else {
        Toast.makeText(this, "Location permission is denied, please allow the permission", Toast.LENGTH_LONG).show();
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_PERMISSIONS_REQUEST_CODE);

    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    getLocation();     
     
}

Upvotes: 1

Views: 140

Answers (1)

Jonathan Kalush
Jonathan Kalush

Reputation: 223

I had the same problem try this code it works for me(assuming your map works fine):

package il.co.jonathan.monstercatch.ACTIVITIES;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

import il.co.jonathan.monstercatch.R;

public class Game_Activity extends FragmentActivity implements OnMapReadyCallback {

    private Location currentLocation;
    private LocationCallback locationCallback;

    private FusedLocationProviderClient fusedClient;
    private static final int REQUEST_CODE =101;
    private FrameLayout map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        map=findViewById(R.id.map);
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                if(locationResult == null){
                    return;
                }
                for (Location location : locationResult.getLocations()){
                    if(location != null){
                        currentLocation = location;
                    }
                }
            }
        };

        fusedClient = LocationServices.getFusedLocationProviderClient(this);
        getLocation();
    }
    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_CODE);
            return;
        }

            Task<Location> task = fusedClient.getLastLocation();

            task.addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        currentLocation = location;
                        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                        assert supportMapFragment != null;
                        supportMapFragment.getMapAsync(Game_Activity.this);
                    }
                }
            });
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        googleMap.getUiSettings().setScrollGesturesEnabled(false);
            LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Player");
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
            googleMap.addMarker(markerOptions);
    }
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults){
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
        if(requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLocation();
            }
        }
    }

}

feel free to contact me if this doesn't work

Upvotes: 1

Related Questions