0

I trying to get the location using network/gps.

I define add the permission on the manifest ( ACCESS_FINE_LOCATION ) but i getting that the permission is -1 ( PERMISSION_DENIED )

I calling a instance of the class 'GetLocation' on the main activity. And call the 'getCurrentLocation(this)' from this main activity.

The code:

  public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TraceActionLocation t = new TraceActionLocation();

    Location l = t.getCurrentLocation(this);


}


  public class GetLocation
  {
    public Location getCurrentLocation(Context context)
    {
        Location location = null;

    LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

    Boolean isGpsEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    Boolean isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if(!isGpsEnable && !isNetworkEnable)
    {
        // TODO !!! => no gps and no network !!!
    }
    else if(context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_DENIED)
    {
        // 1. get the location from network provider
        if(isNetworkEnable)
        {
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }

        // 2. get the more equate location from the gps
        if(isGpsEnable)
        {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
    }

    return location;
}
}
Yanshof
  • 9,659
  • 21
  • 95
  • 195

1 Answers1

-2

Obtaining user location from a mobile device can be complicated. There are several reasons why a location reading (regardless of the source) can contain errors and be inaccurate. Some sources of error in the user location include:

Multitude of location sources GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency. User movement Because the user location changes, you must account for movement by re-estimating user location every so often. Varying accuracy Location estimates coming from each location source are not consistent in their accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest location from another or same source.

Requesting user permission... ...

Mahachi
  • 11
  • 3