以编程方式检索Google Ads版本

时间:2019-02-27 13:28:45

标签: android admob google-ads-api

我正在使用最新的google ads sdk版本admob(通过gradle)

implementation 'com.google.android.gms:play-services-ads:17.1.1'

,我正在尝试以编程方式检索版本。在IOS中,该版本是通过[GADRequest sdkVersion]检索的,但我找不到在android中检索它的方法

1 个答案:

答案 0 :(得分:0)

要检索Google Ads SDK版本,简单的解决方案是在gralde文件中声明该版本,然后直接在代码中使用它。

build.gradle(Module: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;
}