使用GPS获取用户当前和确切位置 [英] Get user current and exact location using GPS
本文介绍了使用GPS获取用户当前和确切位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的新应用,我需要使用GPS获取用户位置。为此,我正在使用 fusedLocationProviderApi.getLastLocation
。大多数时候我得到 null
。但是后来我意识到所有的API都是为了在位置上发生变化而得到通知。但我想在应用程序中获取用户的当前确切位置(请考虑用户不要移动)。
如何获取Location对象,以便每次都不会获取 null
。
OnCreate()方法中使用此代码来获取位置
//获取对系统位置管理器的引用
LocationManager locationManager =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
//定义一个响应位置更新的侦听器
LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location){
// //当网络位置提供者找到新的位置。
makeUseOfNewLocation(location);
$ b $ public void onStatusChanged(String provider,int status,Bundle extras){}
$ b $ public void onProviderEnabled(String provider){}
public void onProviderDisabled(String provider){}
};
//使用位置管理器注册侦听器以接收位置更新
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
For my new app, I need to get user location using GPS. To do so, I am using fusedLocationProviderApi.getLastLocation
. Most of the time I am getting null
.
But then I realized that all the APIs are intended to get notified on Location changed. But I want to take current exact location of user (consider user not moving) in the app.
How do I get the Location object so that I don't get null
each time.
解决方案
You can use this code in OnCreate()
method to get location
// 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.NETWORK_PROVIDER, 0, 0, locationListener);
这篇关于使用GPS获取用户当前和确切位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文