SoFunction
Updated on 2025-04-20

Android Studio's method to obtain configuration resources and third-party package information

1. Obtain the configuration in the resource file

1. Get the color value

res/values/Definition in  :

<color name="colorPrimary">#3F51B5</color>
<color name="colorAccent">#FF4081</color>

How to get it

Get it in Java:

// Get color value (int type, including alpha channel)int color = getResources().getColor(, getTheme());

// Compatible with old versionsint color = (context, );

Get it in Kotlin:

// Directly extend the function methodval color = (context, )

// Or use resource extensionval color = ()

2. Get the string

res/values/Definition in  :

<string name="app_name">MyApplication</string>
<string name="welcome_message">Hello, %s!</string>

How to get it

Get it in Java:

// Get a normal stringString appName = getResources().getString(.app_name);

// Get a string with parametersString welcomeMsg = getResources().getString(.welcome_message, "John");

Get it in Kotlin:

// Get a normal stringval appName = (.app_name)

// Get a string with parametersval welcomeMsg = getString(.welcome_message, "John")

3. Get the size value

res/values/Definition in  :

<dimen name="padding_medium">16dp</dimen>

How to get it

Get it in Java:

// Get pixel value (dp/sp will be automatically converted to px)float padding = getResources().getDimension(.padding_medium);

// Get the exact pixel value (no rounding)float paddingExact = getResources().getDimensionPixelSize(.padding_medium);

Get it in Kotlin:

val padding = (.padding_medium)
val paddingExact = (.padding_medium)

4. Get integer/boolean value

res/values/Definition in  :

<integer name="max_count">10</integer>
<bool name="is_debug">true</bool>

How to get it

Get it in Java:

int maxCount = getResources().getInteger(.max_count);
boolean isDebug = getResources().getBoolean(.is_debug);

Get it in Kotlin:

val maxCount = (.max_count)
val isDebug = (.is_debug)

5. Get the array

res/values/Definition in  :

<string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
</string-array>

<integer-array name="numbers_array">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</integer-array>

How to get it

Get it in Java:

String[] planets = getResources().getStringArray(.planets_array);
int[] numbers = getResources().getIntArray(.numbers_array);

Get it in Kotlin:

val planets = (.planets_array)
val numbers = (.numbers_array)

2. Obtain application package information

1. Obtain current application information

Java/Kotlin general method:

// Get package informationPackageManager pm = ();
String packageName = ();

try {
    PackageInfo packageInfo = (packageName, 0);
    
    // Application version information    String versionName = ;
    int versionCode = ; // Note: Use long type versionCode in the new API    
    // Application name    String appName = ().toString();
    
    // Application icon    Drawable appIcon = (packageName);
    
} catch ( e) {
    ();
}

Kotlin simplified version:

val pm = 
val packageName = 

try {
    val packageInfo = (packageName, 0)
    
    val versionName = 
    val versionCode =  // Pay attention to using longVersionCode    
    val appName = ().toString()
    val appIcon = (packageName)
    
} catch (e: ) {
    ()
}

2. Obtain other application information

// Check whether the application is installedboolean isAppInstalled = isPackageInstalled("", context);

public static boolean isPackageInstalled(String packageName, Context context) {
    try {
        ().getPackageInfo(packageName, 0);
        return true;
    } catch ( e) {
        return false;
    }
}

// Get the installed app listList&lt;ApplicationInfo&gt; apps = ().getInstalledApplications(0);
for (ApplicationInfo appInfo : apps) {
    String appName = (()).toString();
    String packageName = ;
    Drawable icon = (());
    // Process application information...}

3. Obtain third-party dependency package information

1. Use BuildConfig to get the dependency version

Gradle will automatically generate a BuildConfig class for each dependency library, and can obtain version information:

// Get the Gson library versionString gsonVersion = .VERSION_NAME;

// Get the Glide library versionString glideVersion = .VERSION_NAME;

2. Get dependency information through PackageManager

// Get all installed package informationList&lt;PackageInfo&gt; packages = getPackageManager().getInstalledPackages(0);

for (PackageInfo packageInfo : packages) {
    if ((".") || 
        (".")) {
        // This is a library from Google or Facebook        String packageName = ;
        String versionName = ;
        int versionCode = ;
    }
}

3. Use reflection to obtain internal information (not recommended, only for understanding)

try {
    Class<?> clazz = ("");
    Field versionField = ("VERSION");
    String version = (String) (null);
} catch (Exception e) {
    ();
}

4. Dynamically obtain resource ID

Sometimes we need to dynamically obtain the resource ID based on the resource name:

// Get the resource IDpublic static int getResourceId(Context context, String resourceName, String type) {
    return ().getIdentifier(resourceName, type, ());
}

// Use exampleint colorId = getResourceId(context, "colorPrimary", "color");
int stringId = getResourceId(context, "app_name", "string");
int drawableId = getResourceId(context, "ic_launcher", "drawable");

5. Obtain the theme attributes

Get attribute values ​​from the current topic:

// Create a TypedArrayTypedArray typedArray = ().obtainStyledAttributes(new int[]{});

try {
    // Get color value    int colorPrimary = (0, );
} finally {
    ();
}

6. Multilingual resource acquisition

Get resources for a specific locale:

// Create configuration for a specific LocaleConfiguration config = new Configuration(());
(new Locale("es")); // Spanish
// Create a new ContextContext localizedContext = (config);

// Get resources with new ContextString localizedString = ().getString(.welcome_message);

Best Practice Recommendations

  1. Resource acquisition optimization

    • Avoid frequent acquisition of resources in loops
    • Get common resources early in the Activity/Fragment life cycle and cache them
  2. Null value processing

    • Always check if the resource exists
    • Provide default values ​​for methods such as getString()
  3. Performance considerations

    • Ensure backward compatibility using compatible classes such as ContextCompat
    • Note that TypedArray must be recycle() after use
  4. Security

    • Handle permission issues when obtaining information about other applications
    • Don't expose sensitive information in BuildConfig
  5. Resource naming specifications

    • Use consistent naming conventions (such as colorPrimary, text_heading, etc.)
    • Avoid hard-coded resource IDs

Through the above methods, you can flexibly obtain various resources from the configuration files of Android applications and obtain package information of applications and third-party libraries, providing more possibilities for application development.

The above is the detailed content of Android Studio's method to obtain the configuration resources and third-party package information. For more information about Android Studio's configuration resources and third-party package information, please follow my other related articles!