我正在使用最新的谷歌广告sdk版本admob(通过gradle)
implementation 'com.google.android.gms:play-services-ads:17.1.1'
我正在尝试以编程方式检索版本。在IOS中,版本是通过[GADRequest sdk Version]检索的,但我找不到如何在android中检索它
要检索Google Ads SDK版本,简单的解决方案是在gradle文件中声明版本,然后直接在代码中使用它。
build.gradle(模块:app)
// [Step 1] Declare Google Ads SDK version
ext.google_ads_sdk_version = '17.1.1'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.kotlinapp"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// [Step 2] Add a new static variable named GOOGLE_ADS_SDK_VERSION
// in BuildConfig.java file for release build
buildConfigField("String", "GOOGLE_ADS_SDK_VERSION", "$google_ads_sdk_version")
}
debug {
// [Step 3] Add a new static variable named GOOGLE_ADS_SDK_VERSION
// in BuildConfig.java file for debug build
buildConfigField("String", "GOOGLE_ADS_SDK_VERSION", "\"$google_ads_sdk_version\"")
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
// [Step 4] Add the version to google ads dependency
implementation "com.google.android.gms:play-services-ads:$google_ads_sdk_version"
}
在java代码中
Log.i("TAG", BuildConfig.GOOGLE_ADS_SDK_VERSION);
额外:另一种方法是使用以下方法,限制是它仅适用于Google Ads SDK版本为15.0.0或更高版本。
/**
* Gets Ads SDK version
*
* @return The version or null if the version is not found for some reasons.
*/
public String getAdsSDKVersion() {
InputStream input = null;
try {
input = getClass().getResourceAsStream("/play-services-ads.properties");
Properties prop = new Properties();
prop.load(input);
return prop.getProperty("version");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}