You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中使用ids.xml生成的ID作为权限请求码报错问题咨询

Why IDs from ids.xml Break Permission Requests (And How to Fix It)

Great question—let me walk you through exactly what's happening here and how to fix it.

First, the Root Cause

When you define IDs in res/values/ids.xml, Android generates 32-bit resource IDs that include metadata about the resource type (like "id" vs "string" vs "layout"). For example, an ID from ids.xml might look like 0x7f080001 in hex, which translates to a decimal value way larger than 65535.

Here's the problem: Android's permission request system expects request codes to be 16-bit integers (0 to 65535). When you pass a 32-bit resource ID, the system will often truncate the higher bits, leading to duplicate request codes, invalid values, or outright crashes.

Compare this to PendingIntent: it doesn't have this 16-bit restriction, so using ids.xml IDs works perfectly there—no truncation, no conflicts.

Fixes to Try

Here are two solid ways to handle permission request codes correctly:

1. Use a Static Constant Class

Create a dedicated class to hold all your permission request codes as plain integers (keeping them under 65536):

public class PermissionRequestCodes {
    public static final int REQUEST_CAMERA = 1001;
    public static final int REQUEST_LOCATION = 1002;
    public static final int REQUEST_STORAGE = 1003;
    // Add more as needed
}

Then reference them directly in your code:

ActivityCompat.requestPermissions(this, 
    new String[]{Manifest.permission.CAMERA}, 
    PermissionRequestCodes.REQUEST_CAMERA);

This is the most straightforward approach and avoids any resource ID quirks.

2. Define Integers in integers.xml

If you prefer keeping values in resource files (for consistency), use res/values/integers.xml instead of ids.xml. This file stores pure numeric values without the resource type metadata:

<!-- res/values/integers.xml -->
<resources>
    <integer name="permission_request_camera">1001</integer>
    <integer name="permission_request_location">1002</integer>
</resources>

Retrieve them in code like this:

int cameraRequestCode = getResources().getInteger(R.integer.permission_request_camera);
ActivityCompat.requestPermissions(this, 
    new String[]{Manifest.permission.CAMERA}, 
    cameraRequestCode);

These integers are stored as raw 16/32-bit values, but as long as you keep them under 65536, they'll work perfectly for permission requests.

Key Takeaway

ids.xml IDs are designed for identifying UI elements or other resources, not for numeric request codes that have strict bit-length requirements. Stick to plain constants or integers.xml for permission requests, and you'll avoid those frustrating errors.

内容的提问来源于stack exchange,提问作者Michael Dodd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:34:19