如何获取当前运行应用的活跃Fragment名称?代码混淆下的替代方案
Great question—obfuscation definitely messes with the usual adb shell dumpsys activity trick for inspecting active Fragments. Here are a few practical methods I’ve relied on in similar situations:
Add debug-only lifecycle logging
The easiest way for debug builds is to log the Fragment’s real class name directly in its lifecycle methods (likeonAttachoronResume). UseBuildConfig.DEBUGto ensure these logs only show up in non-release builds, so you don’t bloat production code:override fun onAttach(context: Context) { super.onAttach(context) if (BuildConfig.DEBUG) { Log.d("FragmentTracker", "Active Fragment: ${this::class.java.canonicalName}") } }For Java, it’s similar:
@Override public void onAttach(Context context) { super.onAttach(context); if (BuildConfig.DEBUG) { Log.d("FragmentTracker", "Active Fragment: " + this.getClass().getCanonicalName()); } }Since debug builds typically skip full obfuscation, this will spit out the real Fragment names straight to Logcat.
Use ProGuard/R8 mapping files for release builds
If you’re dealing with an obfuscated release APK, thedumpsyscommand will return mangled class names (likea.b.c.FragmentX). You can map these back to real names using themapping.txtfile generated during the build process (found inbuild/outputs/mapping/release/for Gradle projects). Just search the mangled name in this file—each line shows the original class name followed by the obfuscated one.Leverage Android Studio’s App Inspection
For debug sessions, App Inspection’s Fragment Inspector is a game-changer. Open it via View > Tool Windows > App Inspection, select your running app, and navigate to the Fragment tab. It’ll show you a visual tree of all active Fragments with their real class names, no command-line hoops required. This works even if you have partial obfuscation enabled in debug builds.Adjust your obfuscation rules (preemptive fix)
If you don’t mind a tiny tradeoff in obfuscation strength, you can configure ProGuard/R8 to keep Fragment class names intact. Add these lines to yourproguard-rules.profile:-keepnames class * extends androidx.fragment.app.Fragment -keepnames class * extends android.app.FragmentThis preserves the original class names while still obfuscating method names and internal logic, so
dumpsyswill continue to return readable Fragment names in all builds.
内容的提问来源于stack exchange,提问作者Sunil

