如何在運行時請求位置權限
在您的程式碼中,您正確檢查位置權限並處理沒有權限的情況的確。但是,要在運行時實際請求權限,您需要使用 ActivityCompat.requestPermissions。
這是更正後的 MainActivity:
public class MainActivity extends AppCompatActivity implements LocationListener { // ... (rest of your code) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE); } else { // Permissions already granted // ... } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { // Permissions granted // ... } else { // Permissions denied // ... } } } // ... (rest of your code) }
其中 PERMISSION_REQUEST_CODE 是一個整數常數,您可以定義以輕鬆引用權限請求。
附加註意事項
<manifest ...> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> </manifest>
以上是如何在Android中請求運行時位置權限?的詳細內容。更多資訊請關注PHP中文網其他相關文章!