android - 在android API 23中获取用户的位置

标签 android gps location

我可以编写获取用户位置的代码,并且在 API < 23 中运行良好。但是在 API 23 及更高版本中,我的代码在日志中不返回任何内容。

更多详情:
我手动启用设备的 GPS。 在第一次运行应用程序请求权限并且没有日志返回。
在下次运行该应用程序时,返回我准备好的 Toast(检查您的提供商)。

这是我写的代码:

public class MainActivity extends AppCompatActivity implements LocationListener {

private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 124;
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 123;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

        } else {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_FINE_LOCATION);
        }
    }
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)) {

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_COARSE_LOCATION);

        }
    }

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location == null) {
        Toast.makeText(this, "Check your provider", Toast.LENGTH_SHORT).show();
    } else {
        Log.i("New Location", "lat: " + location.getLatitude());
        Log.i("New Location", "lng: " + location.getLongitude());
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.i("Location", "lat: " + location.getLatitude());
    Log.i("Location", "lng: " + location.getLongitude());
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

最佳答案

在 Android API 23+ 中,有一种新的方法来处理被视为“危险”的权限,这就是 android.permission.ACCESS_FINE_LOCATIONandroid.permission.ACCESS_COARSE_LOCATION等等。

如果您已经在使用 android.permission.ACCESS_FINE_LOCATION,则无需处理 android.permission.ACCESS_COARSE_LOCATION

请查看官方文档中的此链接,该链接向您展示了如何在 Android API 23+ 中在运行时处理权限。

https://developer.android.com/training/permissions/requesting.html

这个也可能对您有所帮助。

https://developer.android.com/guide/topics/location/strategies.html

如何检查权限:

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
    Manifest.permission.ACCESS_FINE_LOCATION);

如何请求权限:

if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.ACCESS_FINE_LOCATION)
    != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.ACCESS_FINE_LOCATION)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
            MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

        // MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

请注意,即使您在运行时请求权限,您仍然必须像这样在 android list 中保留权限条目:

<manifest ... >
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    ...
    <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
    <uses-feature android:name="android.hardware.location.gps" />
    ...
</manifest>

检查并授予权限后,您应该查看带有上述位置策略的链接,在那里您可以找到您缺少的内容的详细信息。

基本上您没有注册监听器来接收位置更新。在 onCreate() 方法末尾添加此行后,您应该开始在日志中看到位置更新。

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

关于android - 在android API 23中获取用户的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934318/

相关文章:

java - 旋转 ImageView 以面对给定的纬度和经度位置

swift - 从屏幕中心获取位置 Swift MapKit

android - android中动画和交互 View 后点击敏感区域不改变

android - 实时 RTSP 流解码 : large video lag using MediaPlayer on Android

java - 如何在 Android 中处理 ConcurrentModificationException

比较坐标路径的算法

Android 位置包含随机高度值

android - android 上的 opengl es 颜色选择不闪烁

mysql - 如何从每组行的最小和最大时间戳中选择mysql数据

java - 如何在 java/android 中漂亮地格式化 GPS 数据?