所以,我设法做到了:
定义了两种口味
gms {
dimension "services"
buildConfigField "String", "SERVICE_USED", '"g"'
}
hms {
dimension "services"
buildConfigField "String", "SERVICE_USED", '"h"'
}
每当我需要决定执行以下操作时,我都会在代码中使用“g”和“h”:API 需要“android”或“iOS”的deviceType,并且包含华为构建我们定义了另一个常数“华为”。我使用SERVICE_USED 知道要发送什么常量。
然后我在 build.gradle 的顶部做了这个:
apply plugin: 'com.android.application'
if (getGradle().getStartParameter().getTaskRequests().toString().contains("Hms")) {
//*meh*
} else {
apply plugin: 'io.fabric'
}
因为我使用的是fabric(和fabric / firebase ...并不能真正与HMS一起使用),而且我也在build.gradle的最底部这样做了
if (getGradle().getStartParameter().getTaskRequests().toString().contains("Hms")) {
apply plugin: 'com.huawei.agconnect'
} else {
apply plugin: 'com.google.gms.google-services'
}
只包含正确的插件。
然后我开始处理使用gms 的每一件事(地图、位置、推送通知、分析),方法是制作一个包装器并分离每种风格的代码。即对于推送通知,我创建了一个HPushNotif,它有一个getToken 方法。我在两种风格中定义了相同的类和方法,但我根据服务类型(gms 或 hms)来实现它们。
我在项目中包含依赖项时使用了这种类型的表示法:
//GMS stuff
gmsImplementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
gmsImplementation 'com.google.firebase:firebase-core:16.0.9'
gmsImplementation 'com.google.firebase:firebase-messaging:18.0.0'
gmsImplementation 'com.google.firebase:firebase-crash:16.2.1'
gmsImplementation 'com.google.android.gms:play-services-maps:16.1.0'
gmsImplementation 'com.google.android.gms:play-services-location:16.0.0'
gmsImplementation 'com.google.android.gms:play-services-tagmanager:16.0.8'
//HMS stuff
hmsImplementation 'com.huawei.agconnect:agconnect-core:1.0.0.300'
hmsImplementation 'com.huawei.hms:push:4.0.3.301'
hmsImplementation 'com.huawei.hms:maps:4.0.1.301'
hmsImplementation 'com.huawei.hms:location:4.0.3.303'
Implementation 之前的gms 和hms 指的是口味的名称。只有在选择了适当的 BuildVariant(即正在构建适当的风格)时才会加载这些依赖项。
基本上,我为这两种情况包装了地图、分析、位置和推送通知的逻辑。这就是结构的外观。没什么特别的。
就是这样。当他们创建 HMS 时,他们基本上是按类复制 GMS,按方法复制。您将看到确切的方法名称完全匹配,甚至与调用参数和返回值匹配。它们是 99.99% 相同的。这让事情变得更容易。基本上你只需要复制两个类中的代码并导入正确的东西(在类的顶部)。您很少需要更改已为 GMS 编写的代码。
希望对某人有所帮助。