Android上的LocationManager API似乎对一个只需要偶尔粗略估计用户位置的应用程序来说有点麻烦。
我正在开发的应用程序本身并不是一个定位应用程序,但它确实需要获取用户的位置,以便显示附近企业的列表。它不需要担心用户是否在移动或类似的事情。
以下是我想做的:
向用户显示附近位置的列表。预加载用户的位置,以便在“活动X”中需要它时,它将可用。我并不特别关心更新的准确性或频率。只要不太远,只要抓住一个位置就足够了。也许如果我想变得更漂亮,我会每隔几分钟左右更新一次位置,但这不是一个很大的优先事项。适用于任何具有GPS或网络位置提供商的设备。
这似乎并不难,但在我看来,我必须组建两个不同的位置提供商(GPS和NETWORK),并管理每个提供商的生命周期。不仅如此,我还必须在多个活动中复制相同的代码以满足#2。过去,我曾尝试使用getBestProvider()将解决方案简化为仅使用一个位置提供程序,但这似乎只提供了最好的“理论”提供程序,而不是实际会为您提供最佳结果的提供程序。
有没有更简单的方法来实现这一点?
public static Location getBestLocation(Context ctxt) {
Location gpslocation = getLocationByProvider(
LocationManager.GPS_PROVIDER, ctxt);
Location networkLocation = getLocationByProvider(
LocationManager.NETWORK_PROVIDER, ctxt);
Location fetchedlocation = null;
// if we have only one location available, the choice is easy
if (gpslocation != null) {
Log.i("New Location Receiver", "GPS Location available.");
fetchedlocation = gpslocation;
} else {
Log.i("New Location Receiver",
"No GPS Location available. Fetching Network location lat="
+ networkLocation.getLatitude() + " lon ="
+ networkLocation.getLongitude());
fetchedlocation = networkLocation;
}
return fetchedlocation;
}
/**
* get the last known location from a specific provider (network/gps)
*/
private static Location getLocationByProvider(String provider, Context ctxt) {
Location location = null;
// if (!isProviderSupported(provider)) {
// return null;
// }
LocationManager locationManager = (LocationManager) ctxt
.getSystemService(Context.LOCATION_SERVICE);
try {
if (locationManager.isProviderEnabled(provider)) {
location = locationManager.getLastKnownLocation(provider);
}
} catch (IllegalArgumentException e) {
Log.i("New Location Receiver", "Cannot access Provider " + provider);
}
return location;
}
对@Fedor解决方案的改进。我们可以使用位置管理器的requestSingleUpdate方法,而不是使用“0”时间间隔和“0”距离请求位置。更新的代码(kotlin版本)
import android.annotation.SuppressLint
import android.content.Context
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import java.util.*
@SuppressLint("MissingPermission")
class AppLocationProvider {
private lateinit var timer: Timer
private var locationManager: LocationManager? = null
private lateinit var locationCallBack: LocationCallBack
private var gpsEnabled = false
private var networkEnabled = false
private var locationListener: LocationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
timer.cancel()
locationCallBack.locationResult(location)
}
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
}
fun getLocation(context : Context, callBack: LocationCallBack): Boolean {
locationCallBack = callBack
if (locationManager == null)
locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager?
//exceptions will be thrown if provider is not permitted.
try {
gpsEnabled = locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER)
} catch (ex: Exception) {
ex.printStackTrace()
}
try {
networkEnabled = locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (ex: Exception) {
ex.printStackTrace()
}
//don't start listeners if no provider is enabled
if (!gpsEnabled && !networkEnabled)
return false
val criteria = Criteria()
if (gpsEnabled) {
criteria.accuracy = Criteria.ACCURACY_FINE
} else {
criteria.accuracy = Criteria.ACCURACY_COARSE
}
locationManager!!.requestSingleUpdate(criteria, locationListener, null)
timer = Timer()
timer.schedule(GetLastKnownLocation(), 5000)
return true
}
inner class GetLastKnownLocation : TimerTask() {
override fun run() {
locationManager!!.removeUpdates(locationListener)
var netLoc: Location? = null
var gpsLoc: Location? = null
if (gpsEnabled)
gpsLoc = locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (networkEnabled)
netLoc = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
//check which value use the latest one
if (gpsLoc != null && netLoc != null) {
if (gpsLoc.time > netLoc.time)
locationCallBack.locationResult(gpsLoc)
else
locationCallBack.locationResult(netLoc)
return
}
if (gpsLoc != null) {
locationCallBack.locationResult(gpsLoc)
return
}
if (netLoc != null) {
locationCallBack.locationResult(netLoc)
return
}
locationCallBack.locationResult(null)
}
}
interface LocationCallBack {
fun locationResult(location: Location?)
}
}
要获取位置,只需调用getLocation方法-
AppLocationProvider().getLocation(context, object : AppLocationProvider.LocationCallBack {
override fun locationResult(location: Location?) {
// use location, this might get called in a different thread if a location is a last known location. In that case, you can post location on main thread
}
})
注:在调用getLocation方法之前,必须授予所需的位置权限。
你可以一直使用LocationManager.getLastKnownLocation(),但就像它说的那样,它可能已经过时了。
获取一般位置的一个简单方法是注册网络(通常很快)。
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 1000, this);
然后做
locationManager.removeUpdates(this);
在侦听器的onLocationChanged()方法中。
我已经创建了一个小应用程序,并逐步描述以获取当前位置GPS坐标。
以下URL中的完整示例源代码:
获取当前位置坐标,城市名称-在Android中
查看其工作原理:
我们只需要在清单文件中添加此权限<uses permission android:name=“android.permission.ACCESS_FINE_LOCATION”></使用权限>并像这样创建LocationManager实例LocationManager LocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);检查GPS是否已启用然后实现LocationListener和Get CoordinatesLocationListener LocationListener=新的MyLocationListeners();locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10,locationListener);下面是要做的示例代码
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*-------to get City-Name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
editLocation.setText(s);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}