在admob中,可以添加测试设备来测试真实的广告,如下所示:

android 广告平台 开源代码 android广告id_测试设备


而添加测试设备需要一个广告ID,这里简单说下广告ID的获取方式:

像pixel这类官方手机,在setting—> google —>ads中就可以看到:

android 广告平台 开源代码 android广告id_ide_02


但这样很不方便,总不能一个个手工敲,容易出错,所以给出一份代码:

首先AndroidManifest.xml中添加如下代码,注意APPLICATION_ID是必须的,至于value可以随意填

<uses-permission android:name="android.permission.INTERNET"/>
     <application
       ...>
       <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-2678030319750280~1111111111" />

依赖库:

dependencies {
    implementation 'com.google.android.gms:play-services-ads-lite:18.1.1'
    }

代码:

AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
    @Override
    protected String doInBackground(Void... params) {
        AdvertisingIdClient.Info idInfo = null;
        try {
            idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        String advertId = null;
        try{
            advertId = idInfo.getId();
        }catch (NullPointerException e){
            e.printStackTrace();
        }

        return advertId;
    }

    @Override
    protected void onPostExecute(String advertId) {
        Log.e("hgy413", "id:" + advertId);
        Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_LONG).show();
    }

};
task.execute();

也试用了官方的获取指南:https://developer.android.com/training/articles/ad-id 但发现 isAdvertisingIdProviderAvailable会一直返回false,小记下。