Get user current and exact location using GPS [duplicate]

谁说我不能喝 提交于 2020-01-05 11:51:12

问题


For my new app, I need to get user location using GPS. To do so, I am using fusedLocationProviderApi.getLastLocation. Most of the time I am getting null.

But then I realized that all the APIs are intended to get notified on Location changed. But I want to take current exact location of user (consider user not moving) in the app.

How do I get the Location object so that I don't get null each time.


回答1:


You can use this code in OnCreate() method to get location

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);


来源:https://stackoverflow.com/questions/34130261/get-user-current-and-exact-location-using-gps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!