java - 查找当前位置
问题描述
我找不到当前位置,总是找到我最后的位置。
我必须改变什么。
请帮忙。
我的学校项目作业
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpstxt = (TextView) findViewById(R.id.txtgps);
buttonGPS = (Button) findViewById(R.id.gpsbtn);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
final Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
buttonGPS.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onLocationChanged(location);
}
});
}
private void onLocationChanged(Location location) {
double longtitude = location.getLongitude();
double latitude = location.getLatitude();
gpstxt.setText("Enlem:" + latitude + "\n" + "Boylam:" + longtitude);
}
}
不是最后一个位置输出。我想使用 gps 查找当前位置。
解决方案
您似乎正在使用getLastKnownLocation()
为您提供用户最后已知位置的方法。
相反,您应该使用requestLocationUpdates()
locationManager 包中的方法。
像这样的东西应该工作:
// 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.GPS_PROVIDER, 0, 0, locationListener);
参考:https ://developer.android.com/guide/topics/location/strategies.html
推荐阅读
- javascript - 外部功能在页面加载时不起作用,但在按钮按下时起作用
- android - Android,将底部导航与标签相结合(活动与片段)
- html - 在 ":hover" 之后有一个元素停留在结束动画位置吗?
- python - 哪个更快;添加到 pandas 数据框,然后提取到 cvs 或使用文件指针写入文档
- php - 如何循环乘法?
- python - 重塑和过滤熊猫数据框
- aws-lambda - 仅在特定 lambda 请求时才允许完成 cognito AWS API 操作
- c - 使用 qsort 和 void 指针问题对结构进行排序
- node.js - 来自数据库的 HTML 显示为纯文本
- php - Yii2. 无法存储 url 或“