LocationManager 未在 android 8 内执行

LocationManager not execute in android 8

这是我获取位置的代码:

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 上运行?

试试这个

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;
    }
}