Android中使用GAID

在Android系统中,也有一个广告ID类似于iOS系统中的IDFA,这个就是基于Google Play Services的GAID了。但是国产手机的Andoird系统都是阉割掉了Google Play Services,所以是获取不到GAID的。

设置依赖

在gradle中添加google sdk组件

 implementation group: 'com.google.android.gms', name: 'play-services-ads', version: '15.0.0'

获取代码

 //获取 GAID
public String getGAID(){
        String gaid= "";
        AdvertisingIdClient.Info adInfo = null ;
        try {
            adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
            Log.e("getGAID", "IOException");
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
            Log.e("getGAID", "GooglePlayServicesNotAvailableException");
        } catch (Exception e) {
            Log.e("getGAID", "Exception:"+e.toString());
            // Encountered a recoverable error connecting to Google Play services.
        }
        if (adInfo!= null){
            gaid= adInfo.getId();
            Log.w("getGAID", "gaid:"+gaid);
        }
        return gaid;
    }

注意,此方法需要在子线程执行,不然会报错。

0%