如何在运行时请求位置权限
问题:
添加位置权限时清单并在 Android 6 上运行,没有响应或位置更新已收到。
问题:
我做错了什么? (堆栈跟踪中的错误代码为“PERMISSION_DENIED”)
答案:
要在运行时请求位置权限,您需要使用 ActivityCompat 显式请求它。 requestPermissions() 方法。
使用 Kotlin 更新了代码和示例Android 12:
Kotlin:
import android.Manifest.permission.ACCESS_FINE_LOCATION import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import android.provider.Settings import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var locationManager: LocationManager private var provider: String? = null private val locationListener = MyLocationListener() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) locationManager = getSystemService(LocationManager::class.java) provider = locationManager.getBestProvider(null, false) if (checkPermission()) { getLocationUpdates() } else { requestPermission() } } override fun onResume() { super.onResume() if (checkPermission()) { getLocationUpdates() } } override fun onPause() { super.onPause() if (checkPermission()) { locationManager.removeUpdates(locationListener) } } private fun getLocationUpdates() { locationManager.requestLocationUpdates(provider, 0, 0f, locationListener) val location = locationManager.getLastKnownLocation(provider) if (location != null) { onLocationChanged(location) } } private fun onLocationChanged(location: Location) { val latitude = location.latitude val longitude = location.longitude Toast.makeText(this, "Location: Lat: $latitude, Lng: $longitude", Toast.LENGTH_LONG).show() } private fun checkPermission(): Boolean { return ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED } private fun requestPermission() { ActivityCompat.requestPermissions(this, arrayOf(ACCESS_FINE_LOCATION), PERMISSION_REQUEST_CODE) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getLocationUpdates() } else { // Permission denied. AlertDialog.Builder(this)
以上是为什么我在 Android 上请求位置权限时收到'PERMISSION_DENIED”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!