如何在運行時請求位置權限
問題:
添加位置權限並在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中文網其他相關文章!