gpt4 book ai didi

android - getLastKnownLocation 返回 Null 值

转载 作者:行者123 更新时间:2023-11-29 01:42:57 24 4
gpt4 key购买 nike

我正在开发一个 android 应用程序,我在其中尝试了以下代码。此外,我还在我的 xml 文件中添加了所有权限。

public class LbsGeocodingActivity extends Activity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

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

locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);

retrieveLocationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showCurrentLocation();
}
});

}

protected void showCurrentLocation() {

Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
}

}

private class MyLocationListener implements LocationListener {

public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}

public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}

public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}

public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}

}

}

但是我在 getLastKnownLocation 得到的是空值。我正在 Samsung Galaxy Grand 上运行我的项目。请告诉我哪里做错了。

提前致谢。

最佳答案

您的代码看起来很完美,我假设您得到的是 Null,因为您的设备中没有以前的 GPS 值。执行此操作,在您的设备中加载应用程序,移动到开阔的天空,运行应用程序,等待 2 分钟。回到办公室里面,然后执行上面的代码

关于android - getLastKnownLocation 返回 Null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23287104/

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