【问题标题】:LocationManager not execute in android 8LocationManager 不在 android 8 中执行
【发布时间】:2023-04-04 04:43:01
【问题描述】:

这是我获取位置的代码:

LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

Criteria criteria = new Criteria();

String provider = locationManager.getBestProvider(criteria, true);

Location location = locationManager.getLastKnownLocation(provider);


final double latitude = location.getLatitude();
final double longitude = location.getLongitude();

当我在 Android 4.4.2 上测试和调试它时,它运行良好并且可以调试,但是当它在 Android 8 上运行时,代码似乎无法执行并且不可调试

我怎样才能让它在 Android 8 上运行?

【问题讨论】:

  • 您是否请求了运行时权限ACCESS_FINE_LOCATIONACCESS_COARSE_LOCATION
  • @JaydipKalkani 是的,先生,正如我告诉它在 android 4.4.2 中执行的那样
  • 发布 android 8 错误日志
  • @erfan 运行时权限与普通权限不同,Android 6.0以下不需要
  • 是的,我知道它在 android 4.4.2 上运行良好,但从 android 6.0 开始,谷歌添加了运行时权限概念。所以,我向您确认您是否使用“requestPermissions()”方法请求了运行时权限?如果您不这样做,请参考this

标签: android location android-location


【解决方案1】:

试试这个

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                Toast.makeText(this, "Location is needed...", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1234);
            }
        }  else {
           //Permission is already granted. Get your location here

        }
    } else {
        //Do your stuff here for SDK below 23
    }

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 1234:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               //Do your work
            } else {
                Toast.makeText(this, "Location is needed...", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2013-03-18
    相关资源
    最近更新 更多