【问题标题】:How to get location (lat,lng) in API 23 and above in Android Programmatically?如何以编程方式在 Android 的 API 23 及更高版本中获取位置(纬度、经度)?
【发布时间】:2016-07-09 05:30:19
【问题描述】:

我正在开发一个启用 GPS 并获取当前位置的应用程序。我的代码在除 API 23 即 Marshmallows 的所有 android 版本中运行良好。我正在 Nexus 5 (API 23)、Galaxy Note 3 (API 22) 中进行测试。

这是我的代码

    public void program()
{
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());

    if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

        AlertDialog.Builder builder = new AlertDialog.Builder(NearBy.this);
        builder.setTitle("Location Service is Not Active");
        builder.setMessage("Please Enable your location services").setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

            final String cityName = addresses.get(0).getAddressLine(0) + " ";
            String stateName = addresses.get(0).getAddressLine(1) + " ";
            String countryName = addresses.get(0).getAddressLine(2) + " ";
            String country = addresses.get(0).getCountryName() + " ";
            String Area = addresses.get(0).getSubAdminArea() + " ";
            String Area1 = addresses.get(0).getAdminArea() + " ";
            String Area2 = addresses.get(0).getLocality() + " ";
            String Area3 = addresses.get(0).getSubLocality();
            Log.e("Locaton", cityName + stateName + countryName + country + Area + Area1 + Area2 + Area3);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
}

我在

处收到 NullpointerException
         addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

仅在 Nexus 5 (API 23) 中。我还在 Mainfest 和运行时授予了权限(ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION)。

请为此提供解决方案。

更新

我更改了我的代码。我创建了一个 GPSTracker 类,我得到了 lat,Lng 为 0

GPSTracker.java

  public class GPSTracker extends Activity implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);


        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled && !isNetworkEnabled) {

        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }

            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return location;
}
@TargetApi(Build.VERSION_CODES.M)
public void stopUsingGPS() {
    if (locationManager != null) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        locationManager.removeUpdates(GPSTracker.this);
    }
}


public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    return latitude;
}

public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    return longitude;
}


public boolean canGetLocation() {
    return this.canGetLocation;
}


public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    alertDialog.setTitle("GPS is settings");

    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    alertDialog.show();
}

@Override
public void onLocationChanged(Location currentLocation) {

    this.location = currentLocation;
    getLatitude();
    getLongitude();

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onProviderEnabled(String provider) {


}

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

}
}

【问题讨论】:

  • 你能发布 logcat 输出吗?
  • 您应该检查运行时权限,例如 if ( Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(上下文,android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return ; }
  • GPSTracker.java 帮助我获取邮政编码 - 谢谢!

标签: android android-6.0-marshmallow android-location android-gps


【解决方案1】:

问题

The location obtained may be null if the last know location could not be found due to various reasons. Read about it in the docs [here][2]

原因/我如何调试它

  1. getFromLocation 不会根据文档抛出空指针,因此问题出在您的位置对象中。

    Read here about this method

补救措施

Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

检查上一步获取的位置是否不为空,然后继续进行地理编码。

代码 sn-p

...
else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if(location == null) {
       log.d("TAG", "The location could not be found");
       return; 
    }
    //else, proceed with geocoding.
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());

获取位置 - 示例

Read here

完整代码

View it here

【讨论】:

  • 如果问题出在我的位置,那么我将如何在 API 22 及更低版本中运行的其他设备中使用相同的代码获得 lat,lng。实际上现在我创建了一个 GPSTracker.java,我得到 lat 和 lng 为 0
  • @AnishKumar :只有在 lastKnownLocation 可用的情况下,这在其他设备中才有可能。尝试在这些设备中打印位置对象,您会自己看到
  • 很好@cafebabe1991。我会尽快通知您。
  • 03-22 17:04:13.964 32141-32141/prateektechnosoft.com.demoproject W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference 03-22 17:04:13.965 32141-32141/prateektechnosoft.com.demoproject W/System.err: at prateektechnosoft.com.demoproject.NearBy.program(NearBy.java:92) 03-22 17:04:13.965 32141-32141/prateektechnosoft.com.demoproject W/System.err: at prateektechnosoft.com.demoproject.NearBy.onCreate(NearBy.java:54)
  • 03-22 17:04:13.957 32141-32141/prateektechnosoft.com.demoproject D/la: Latitude:0.0, Longitude:0.0 03-22 17:04:13.963 32141-32141/prateektechnosoft.com.demoproject D/Location Object: null
【解决方案2】:

首先在棉花糖中添加运行时的所有权限。否则请重启手机后再检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多