gpt4 book ai didi

java - Android 中的位置为空

转载 作者:行者123 更新时间:2023-12-01 11:41:08 26 4
gpt4 key购买 nike

我正在尝试获取我的位置。但我所拥有的一切都是零。请看代码:

 public class ListBranchesActivity extends Activity {       

private double lat, lon;

private LocationManager lm;
private Location location;

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
lon = location.getLongitude();
lat = location.getLatitude();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}
};

然后在onCreate()中的某个地方:

lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10,
locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

以下代码返回 NullPointerException:

   Log.w("es09", "coordinates are " + lon + " " + lat +" " +location.getLatitude()+" "+ location.getLongitude());

该代码返回“坐标为 0.0 0.0”

 Log.w("es09", "coordinates are " + lon + " " + lat);

我的 list 权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_GPS"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS"/>

出了什么问题?

最佳答案

问题是您假设您总是能找回位置,但事实并非如此。无法保证位置会返回给您,因此您必须检查是否为空。

使用

lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

不能保证最后一个位置存在,每当您获得一个位置时,您始终应该首先检查以确保它不为空!

关于java - Android 中的位置为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29516812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com