在运行时请求位置权限
您面临的问题是您需要显式请求位置访问权限。请按照以下步骤解决该问题:
以下是包含权限请求逻辑的代码更新版本:
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中文网其他相关文章!