I think the most maintainable solution is to use dependency injection with different source sets for different flavors. You can put your GMS dependent code inside src/gms/java
and your HMS dependent code inside src/hms/java
. Only the selected product flavor source set will be compiled. Very basic example with Hilt would look like this:
Inside your main source set you will have
src/main/java/your/package/AppMobileServices.kt
interface AppMobileServices {
val isAvailable: Boolean
}
Then for GMS source set
src/gms/java/your/package/GmsModule.kt
:
@Module
@InstallIn(SingletonComponent::class)
class GmsModule {
@Provides
fun googleMobileServices(@ApplicationContext context: Context): AppMobileServices {
return GmsServices(context)
}
}
src/gms/java/your/package/GmsServices.kt
:
@Singleton
class GmsServices(@ApplicationContext private val context: Context) : AppMobileServices {
override val isAvailable: Boolean
get() = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
}
And then HMS source set
src/hms/java/your/package/HmsModule.kt
:
@Module
@InstallIn(SingletonComponent::class)
class HmsModule {
@Provides
fun huaweiMobileServices(@ApplicationContext context: Context): AppMobileServices {
return HmsServices(context)
}
}
src/hms/java/your/package/HmsServices.kt
:
@Singleton
class HmsServices(@ApplicationContext private val context: Context) : AppMobileServices {
override val isAvailable: Boolean
get() = HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS
}
Then in your main source set you can just inject the AppMobileServices
and the correct one will be provided. Also, all code that is dependent on either GMS or HMS would go inside their flavor source sets.
@Inject
lateinit var appMobileServices: AppMobileServices
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…