如何在不使用正则表达式的情况下获取不含applicationIdSuffix的Android包名?
Got it, I totally get why you don’t want to mess with regex here—package names can have all sorts of edge cases, so keeping things straightforward is way better. Here are a few solid, regex-free ways to grab that original base package name, even when getPackageName() returns the suffixed version:
1. Use BuildConfig.APPLICATION_ID
This is probably the simplest approach. The BuildConfig class auto-generates an APPLICATION_ID field that directly maps to the base applicationId you defined in your build.gradle (or build.gradle.kts) file—it doesn’t include any build type suffixes.
Just call it directly in your code:
val basePackageName = BuildConfig.APPLICATION_ID
String basePackageName = BuildConfig.APPLICATION_ID;
Note: Make sure your module has BuildConfig enabled. It’s on by default, but if you’ve disabled it with buildConfigField false, you’ll need to re-enable it in your module’s build file.
2. Fetch originalPackageName from ApplicationInfo
Android keeps track of the original package name (the one you set before any build suffixes) in the app’s ApplicationInfo object. You can retrieve it using the PackageManager:
Kotlin:
fun getBasePackageName(context: Context): String? { return try { val appInfo = context.packageManager.getApplicationInfo( context.packageName, 0 ) appInfo.originalPackageName } catch (e: PackageManager.NameNotFoundException) { // Handle exception if needed null } }
Java:
public String getBasePackageName(Context context) { try { ApplicationInfo appInfo = context.getPackageManager() .getApplicationInfo(context.getPackageName(), 0); return appInfo.originalPackageName; } catch (PackageManager.NameNotFoundException e) { // Handle exception return null; } }
This works because originalPackageName holds the package name as declared in your AndroidManifest.xml (or the base applicationId from gradle) before any build type modifications.
3. Define a Custom Build Config Field
If you want explicit control, you can add a custom field to your build config that hardcodes your base package name. This is useful if your applicationId differs from your actual code package structure, or if you want to avoid relying on auto-generated fields:
Add this to your module’s build.gradle (or build.gradle.kts):
android { defaultConfig { buildConfigField "String", "BASE_PACKAGE_NAME", "\"com.newproject.name\"" } }
Then access it in code like this:
val basePackageName = BuildConfig.BASE_PACKAGE_NAME
String basePackageName = BuildConfig.BASE_PACKAGE_NAME;
Why getPackageName() Returns the Suffixed Version
Just to clarify: When you use applicationIdSuffix in your build types, Gradle modifies the final package name that gets installed on the device. getPackageName() returns this installed package name, which includes the suffix. The methods above bypass this by accessing the original, unmodified value directly from your build config or system metadata.
内容的提问来源于stack exchange,提问作者Vamshi

