java - API 23 本地位置不可用

标签 java android location

我尝试获取设备当前所在的国家/地区,为了获取此信息,我使用 LocationManager,如下所示:

LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    Log.d(TAG, "Network: " + location);
    if(location == null){
      location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
      Log.d(TAG, "GPS: " + location);
    }

在我的 XML 中,我插入了必要的权限:

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.INTERNET"/>

当然,我在运行时请求这些权限。 我的问题是我的目标设备总是给我null,我不知道为什么。但还安装了另一个位置应用程序,它也会下载 map fragment 。有什么想法吗?

最佳答案

据我所知,您不能直接通过 LocationManager 定义国家/地区,因为 Location 类不包含此类数据:

/**
 * A data class representing a geographic location.
 *
 * <p>A location can consist of a latitude, longitude, timestamp,
 * and other information such as bearing, altitude and velocity.
 *
 * <p>All locations generated by the {@link LocationManager} are
 * guaranteed to have a valid latitude, longitude, and timestamp
 * (both UTC time and elapsed real-time since boot), all other
 * parameters are optional.
 */
public class Location implements Parcelable {

您可以定义当前的纬度经度并向某些第三方API发出请求以通过这些坐标定义国家/地区名称。

<小时/>

显然,locationManager.getLastKnownLocation 返回 null,因为您的应用程序的该设备的最后已知位置尚未定义。

/**
 * Returns a Location indicating the data from the last known
 * location fix obtained from the given provider.
 *
 * <p> This can be done
 * without starting the provider.  Note that this location could
 * be out-of-date, for example if the device was turned off and
 * moved to another location.
 *
 * <p> If the provider is currently disabled, null is returned.
 *
 * @param provider the name of the provider
 * @return the last known location for the provider, or null
 *
 * @throws SecurityException if no suitable permission is present
 * @throws IllegalArgumentException if provider is null or doesn't exist
 */
@RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
public Location getLastKnownLocation(String provider) {

就您使用 LocationManager.getLastKnownLocation() 而言,该设备上的任何其他应用程序使用位置数据并不总是重要的。 为了能够正确地重用此设备上其他应用程序接收的位置数据,请阅读有关 fused location provider 的信息。

关于java - API 23 本地位置不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57736866/

相关文章:

android - 在 LooperThread 中获取处理程序返回 null

swift - Swift Playground 中的 CoreLocation

ios - 用户允许位置使用后如何更新我的 View

java - Spring @RequestBody 和枚举值

java - 如何在 win7 64 位上使用 javaFX 在网络摄像头上拍摄图像?

java - 如何在 Java 文档中绘制 UML?

java - 我希望这段代码从 android studio 循环

Android Studio 渲染错误

ios - 如何使用 Xamarin 表单在 iOS 中设置 GPS 位置确认弹出窗口的间隔时间

Java快钱代表?