android 为什么当我请求后台位置时权限对话框不出现?

zbdgwd5y  于 2023-11-15  发布在  Android
关注(0)|答案(3)|浏览(173)

我正在尝试为我的应用请求后台位置权限,但如果我请求后台位置,则位置权限对话框根本不会显示。如果我只请求粗略位置和精细位置,则权限对话框会正常显示。
清单:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"  />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

字符串
验证码:

requestPermissionsIfNecessary(new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
            Manifest.permission.RECEIVE_BOOT_COMPLETED

    });

    ...
    ...
    private void requestPermissionsIfNecessary(String[] permissions) {
    ArrayList<String> permissionsToRequest = new ArrayList<>();
    for (String permission : permissions) {
        if (ContextCompat.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
            permissionsToRequest.add(permission);
        }
    }
    if (permissionsToRequest.size() > 0) {

        ActivityCompat.requestPermissions(
                this,
                permissionsToRequest.toArray(new String[0]),
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}


没有权限对话框出现此代码.但是,如果我注解了'后台'权限行,对话框出现,用户可以选择权限.相同的结果是否针对Android 11或12.那么我在这里错过了什么?

6jjcrrmo

6jjcrrmo1#

这是android 10的预期行为。后台位置权限不能从应用程序授予用户权限。相反,你应该告诉用户某种弹出窗口,并将用户重定向到设置页面。

mrphzbgm

mrphzbgm2#

好吧,在@alokHarman和其他线程的帮助下,我已经达到了以下(在OnCreate中):

if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(intent);
    }
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (!pm.isIgnoringBatteryOptimizations(getPackageName())) {
        Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        startActivity(intent);
    }

字符串
我还指示用户更改此应用程序的电源设置,因为如果允许应用程序进入深度睡眠,则无论后台位置是否激活都无关紧要。

ekqde3dh

ekqde3dh3#

为了请求ACCESS_BACKGROUND_LOCATION,您首先需要请求ACCESS_FINE_LOCATIONACCESS_COARSE_LOCATION。在获得这些权限后,您可以请求ACCESS_BACKGROUND_LOCATION,它会将您重定向到位置权限设置。如果您接受ALLOW_ALL_THE_TIME选项,则授予后台位置权限。
查看下面的代码以获取更多信息:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Check and request location permissions when the activity is created
    checkLocationPermissions()
}

private fun checkLocationPermissions() {
    if (ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    ) {
        // Location permission already granted
        checkBackgroundLocation()
    } else {
        // Location permission not granted, request it
        showLocationPermissionDialog()
    }
}

private fun showLocationPermissionDialog() {
    // Display a dialog to explain why the app needs location permission
    val dialogBuilder = AlertDialog.Builder(this)
    dialogBuilder
        .setMessage("This app requires location permission for XYZ reasons.")
        .setPositiveButton("Grant Permission") { dialog, which ->
            requestLocationPermission()
        }
        .setNegativeButton("Cancel") { dialog, which ->
            // Handle cancellation
        }
        .show()
}

private fun requestLocationPermission() {
    // Request location permission
    ActivityCompat.requestPermissions(
        this,
        arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
        LOCATION_PERMISSION_REQUEST_CODE
    )
}

private fun checkBackgroundLocation() {
    // Check for background location permission on Android Q (API level 29) and above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
        ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        // Request background location permission
        requestBackgroundLocationPermission()
    } else {
        // Background location permission not required or already granted
        // Do further processing or start location updates
        startLocationUpdates()
    }
}

private fun requestBackgroundLocationPermission() {
    // Request background location permission
    ActivityCompat.requestPermissions(
        this,
        arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
        BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE
    )
}

@RequiresApi(Build.VERSION_CODES.M)
override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    when (requestCode) {
        LOCATION_PERMISSION_REQUEST_CODE -> {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Location permission granted
                checkBackgroundLocation()
            } else {
                // Handle when location permission is denied
                handlePermissionDenied()
            }
        }
        BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE -> {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Background location permission granted
                // Do further processing or start location updates
                startLocationUpdates()
            } else {
                // Handle when background location permission is denied
                handlePermissionDenied()
            }
        }
        else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}

private fun startLocationUpdates() {
    // Code to start location updates
}

private fun handlePermissionDenied() {
    // Display a toast indicating that permission is denied
    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()

    // Check if the denial is not permanent
    if (ActivityCompat.shouldShowRequestPermissionRationale(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    ) {
        // Show a rationale or redirect to app settings
        showRationaleOrRedirectToSettings()
    }
}

private fun showRationaleOrRedirectToSettings() {
    // Show rationale or redirect to app settings
    // This is where you can display a message explaining why the permission is necessary
    // and provide an option to open app settings for manual permission grant
}

字符串
First grant foreground location permissions
Then request for ACCESS_BACKGROOUND_LOCATION .

相关问题