Cara Meminta Kebenaran Lokasi pada Masa Jalan
Masalah:
Apabila menambahkan kebenaran Lokasi ke manifes dan berjalan pada Android 6, tiada respons atau kemas kini lokasi diterima.
Soalan:
Apa yang saya buat salah? (Kod ralat dalam surih tindanan ialah 'PERMISSION_DENIED')
Jawapan:
Untuk meminta kebenaran Lokasi semasa runtime, anda perlu memintanya secara eksplisit menggunakan ActivityCompat. kaedah requestPermissions().
Kod dikemas kini dengan Kotlin dan Contoh untuk 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)
Atas ialah kandungan terperinci Mengapa Saya Mendapat Ralat 'PERMISSION_DENIED' Apabila Meminta Kebenaran Lokasi pada Android?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!