gpt4 book ai didi

java - Google API - getLastKnownLocation 的 NULL 指针

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:54 24 4
gpt4 key购买 nike

昨天我的应用程序运行良好,但今天早上它开始崩溃。我认为触发因素是我重新启动了我的智能手机,所以我的应用程序丢失了 GPS 数据。我启动了 Debug模式并逐步查找 NULL 值,我实际上通过以下命令找到了它:

    myLocation = locationManager.getLastKnownLocation(provider);

这会返回一个 NULL 对象,当我尝试使用这些方法时会导致崩溃:

latitude = myLocation.getLatitude();
longtitude = myLocation.getLongitude();

在这种情况下,如何使我的位置不为 NULL?我尝试使用 NETWORK_PROVIDER,但随后我必须使用 WLAN,这不是我认为的最佳方式。我是否仍然可以使用 GPS_PROVIDER 捕获信息,而无需进入保存它们的其他应用程序?

顺便说一句,这是我的代码:

public class gmapps extends FragmentActivity {

private GoogleMap googleMap;
TextView txt_street , txt_city , txt_country ;
Geocoder geocoder;
List<Address> addresses;
ImageView btn_yes;
Location myLocation;
String address , city , country;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
txt_street = (TextView)findViewById(R.id.txt_coordinates);
txt_city = (TextView)findViewById(R.id.txt_city);
txt_country = (TextView)findViewById(R.id.txt_country);
btn_yes = (ImageView)findViewById(R.id.btn_yes);

setUpIfNeeded();

}

private void setUpIfNeeded() {
if (googleMap == null)
{
try{
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}catch(Exception e){}

if (googleMap != null)
{
setUpMap();
}

}
}

private void setUpMap() {

googleMap.setMyLocationEnabled(true);

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria , true);

myLocation = locationManager.getLastKnownLocation(provider); // Here I get the NULL

googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
double latitude = myLocation.getLatitude();
double longtitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude , longtitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));


try {
convert_adresses(latitude,longtitude);
} catch (IOException e) {
e.printStackTrace();
}

txt_street.setText(address);
txt_city.setText(city);
txt_country.setText(country);

}

public void convert_adresses (double lat , double lng) throws IOException
{
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lat, lng, 1);

address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
}

谢谢大家!

最佳答案

首先,您应该使用"new"LocationClent 类(该类已被 LocationServices 取代)。

https://developer.android.com/reference/com/google/android/gms/location/LocationClient.html

使用此类 getLastLocation() 通常效果很好,但正如文档所述(见下文),它有时可能返回 null,因此您必须检查这一点。

您还应该做的是请求位置更新(请参阅上面引用的文档),然后当设备位置可用时,它将在监听器上调用 onLocationChanged(Location location) ,然后您可以执行任何您需要的操作使用提供的位置。

public Location getLastLocation () 

返回当前可用的最佳最新位置。如果位置不可用(这种情况很少发生),将返回 null。将返回在尊重位置权限的同时可用的最佳准确度。此方法提供了一种获取位置的简化方法。它特别适合不需要准确位置且不想维护位置更新的额外逻辑的应用程序。

这是使用位置客户端的精简示例。

public class DeviceLocationClient implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {

private Context context;
private LocationClient locationClient;
private boolean isConnected;
private LocationRequest request;


@Override
public void onLocationChanged(Location location) {
System.out.println("got a location update");
if (location != null ) {
// do something with the location
}
}

public DeviceLocationClient(Context context) {

this.context = context;
System.out.println("connecting to google play services");
locationClient = new LocationClient(context, this, this);
isConnected = false;
locationClient.connect();

}

@Override
public void onConnectionFailed(ConnectionResult result) {
System.out.println("connection to google play services FAILED!");

}

@Override
public void onConnected(Bundle connectionHint) {
System.out.println("google play servies connected");
isConnected = true;
// locationClient.requestLocationUpdates(request, this);
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
isConnected = true;
requestLLocationUpdates();

}

@Override
public void onDisconnected() {
// TODO Auto-generated method stub
System.out
.println("google play services got disconnected - reconnecting");
mBus.unregister(this);
locationClient.connect();

}

@Subscribe
public void onUpdateLocationRequest(UpdateLocationRequest event) {
System.out.println("got the location request");
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
locationClient.removeLocationUpdates(this);
locationClient.requestLocationUpdates(request, this);
}

public void requestLLocationUpdates() {
System.out.println("requesting location updates updates");

if (isConnected) {
System.out.println("processing request");
System.out.println("sending latest location");
Location lastLocation = locationClient.getLastLocation();
if (lastLocation != null) {
// do something with the last location
}
request = new LocationRequest();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setExpirationDuration(60 * 1000);
request.setFastestInterval(5 * 1000);
request.setInterval(10 * 1000);
System.out.println("requesting updates");
locationClient.removeLocationUpdates(this);
locationClient.requestLocationUpdates(request, this);
} else {
if (locationClient.isConnecting()) {
System.out.println("google play services is connecting");
} else {
System.out
.println("attempting to connect to google play services");
locationClient.connect();
}

}
}

}

关于java - Google API - getLastKnownLocation 的 NULL 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25822202/

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