在運行時請求位置權限
您面臨的問題是您需要明確請求位置存取權。請依照以下步驟解決問題:
以下是包含權限請求邏輯的程式碼更新版本:
public class MainActivity extends AppCompatActivity implements LocationListener { private static final int REQUEST_LOCATION_PERMISSION = 10; // ... Other 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.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION); return; } // Perform location-related task if permission is granted // ... } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION_PERMISSION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted, perform location-related task // ... } else { // Permission denied } } } } // ... Other methods ... }
以上是如何在Android運行時請求位置權限?的詳細內容。更多資訊請關注PHP中文網其他相關文章!