Skip to content

Instantly share code, notes, and snippets.

@saurabhkpatel
Last active May 6, 2024 10:43
Show Gist options
  • Save saurabhkpatel/444b26ccb251b60a1bb53f0762035eed to your computer and use it in GitHub Desktop.
Save saurabhkpatel/444b26ccb251b60a1bb53f0762035eed to your computer and use it in GitHub Desktop.
[Android] : Print Activity Flags, it will be useful for the debug.
public static void printActivityFlags(String activityName, Intent intent) {
Field[] declaredFields = Intent.class.getDeclaredFields();
StringBuilder stringBuilder = new StringBuilder(activityName + " => ");
for (Field field : declaredFields) {
if (field.getName().startsWith("FLAG_")) { // Fetch all the flag names which start from "FLAG_"
try {
int flag = field.getInt(null);
if ((intent.getFlags() | flag) == intent.getFlags()) { // checking that flag is present or not.
stringBuilder.append(field.getName());
stringBuilder.append("|");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Log.d("Flags are : " + stringBuilder.toString());
}
@Eightyplus
Copy link

Eightyplus commented Mar 31, 2022

Thanks, here is my suggestion on converting the code to kotlin:

fun Intent.flags(): String =
    Intent::class.java.declaredFields.filter { it.name.startsWith("FLAG_") }.mapNotNull {
        try {
            if (hasFlag(it)) {
                it.name
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }.joinToString()

private fun Intent.hasFlag(field: Field) =
    field.getInt(null).let { flag -> flag or flags == flags }

@cdongieux
Copy link

@Eightyplus

flag -> flag or flags == flag is wrong, it should be flag -> flag or flags == flags

@Eightyplus
Copy link

@cdongieux Thanks 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment