gradleで build variantsを使用して複数のApplication IDを作ったがGCMのレシーバーなどでパッケージ名がバッティングしてしまう時の対処方法
私はgradleを使いこなしていると言うには程遠いレベルですが、Eclipseの時代より楽になった!もう戻れない!
と思うものはbuild variantsなる機能を用いるとリリース用、デバッグ用でパッケージ名やapk名やリソースを簡単に変えられることです。
Configuring Gradle Builds | Android Developers
私もデバッグ用apkはbuildTypesでapplicationIdSuffixに".debug"を付けています。
これによりパッケージ名が変わってくれるので、手間をかけずにリリース用とデバッグ用のapkを同じ端末にインストールすることが出来ています。
buildTypes { debug { debuggable true applicationIdSuffix ".debug" versionNameSuffix "-DEBUG" } }
ところでプッシュ通知を利用している時に限りませんが、permissionやintent-filterの一部にパッケージ名を指定する必要がある時にAndroidManifest.xmlに直書きしていませんか。
このままですと、パッケージが異なるapkが出来てもreceiverに指定したパッケージ名が同じという状態になってしまいます。
同じ端末にインストールすることも出来ません。
この場合、パッケージ名の代わりに${applicationId}を使用すればAndroidManifestを複数用意しなくてもビルドタイプに応じてパッケージ部分をを切り替えてくれます。
※ただしGradle Plugin v0.12以上の場合です。2015/09/09現在最新のバージョンは1.3なのであまり心配はいらないと思います。
参考サイト様stackoverflow.com
${applicationId}で書き換えたAndroidManifest.xmlはこのようになりました。
これでbuild variantsの恩恵も受けられます。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="sakurafish.com.myexamgcm"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <permission android:name="${applicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".RegistrationIntentService"/> <service android:name=".MyGCMListenerservice" android:exported="false" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </service> <service android:name=".MyInstanceIDListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.android.gms.iid.InstanceID"/> </intent-filter> </service> <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="${applicationId}" /> </intent-filter> <intent-filter> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="${applicationId}" /> </intent-filter> </receiver> </application> </manifest>