Android 獲取Google廣告ID (adid)

Android 市面上其實(shí)有很多獲取唯一標(biāo)識的方法,但是海外廣告投放時有很多時候都需要用到廣告ID ,也就是 Google Advertising ID 簡寫 ADID.
在Android系統(tǒng)中提供了了AndroidId玛痊,但AndroidId有時候會為null辰斋,同時root手機(jī)用戶,androidId可以改變。所以AndroidId并不能作為唯一識別碼我注。

對于Google推薦使用Google Advertising ID,通過Google Service可以獲取Google Advertising ID(如果沒有Google Service就獲取不到Google Advertising ID)瞳筏。下面看看代碼吧

AdvertisingIdClient類

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Looper;
import android.os.Parcel;
import android.os.RemoteException;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * date:2020-11-13
 * desc:
 */
public class AdvertisingIdClient {
    /**
     * 這個方法是耗時的卓缰,不能在主線程調(diào)用
     */
    public static String getGoogleAdId(Context context) throws Exception {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            return "Cannot call in the main thread, You must call in the other thread";
        }
        PackageManager pm = context.getPackageManager();
        pm.getPackageInfo("com.android.vending", 0);
        AdvertisingConnection connection = new AdvertisingConnection();
        Intent intent = new Intent(
                "com.google.android.gms.ads.identifier.service.START");
        intent.setPackage("com.google.android.gms");
        if (context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
            try {
                AdvertisingInterface adInterface = new AdvertisingInterface(
                        connection.getBinder());
                return adInterface.getId();
            } finally {
                context.unbindService(connection);
            }
        }
        return "";
    }

    private static final class AdvertisingConnection implements ServiceConnection {
        boolean retrieved = false;
        private final LinkedBlockingQueue<IBinder> queue = new LinkedBlockingQueue<>(1);

        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                this.queue.put(service);
            } catch (InterruptedException localInterruptedException) {
            }
        }

        public void onServiceDisconnected(ComponentName name) {
        }

        public IBinder getBinder() throws InterruptedException {
            if (this.retrieved)
                throw new IllegalStateException();
            this.retrieved = true;
            return this.queue.take();
        }
    }

    private static final class AdvertisingInterface implements IInterface {
        private IBinder binder;

        public AdvertisingInterface(IBinder pBinder) {
            binder = pBinder;
        }

        public IBinder asBinder() {
            return binder;
        }

        public String getId() throws RemoteException {
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            String id;
            try {
                data.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
                binder.transact(1, data, reply, 0);
                reply.readException();
                id = reply.readString();
            } finally {
                reply.recycle();
                data.recycle();
            }
            return id;
        }

        public boolean isLimitAdTrackingEnabled(boolean paramBoolean)
                throws RemoteException {
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            boolean limitAdTracking;
            try {
                data.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
                data.writeInt(paramBoolean ? 1 : 0);
                binder.transact(2, data, reply, 0);
                reply.readException();
                limitAdTracking = 0 != reply.readInt();
            } finally {
                reply.recycle();
                data.recycle();
            }
            return limitAdTracking;
        }
    }
}

其實(shí)在Application類中獲取即可,有一點(diǎn)需要注意就是 這個方法是耗時的,不能在主線程調(diào)用

private void initAdid() {
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String adid = AdvertisingIdClient.getGoogleAdId(getApplicationContext());
                    LogUtils.e(TAG,"adid:"+adid);
                    SPStaticUtils.put(SPKeys.USER_ADID,adid);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
獲取結(jié)果

date:2020.11.13 10:52:31 (周五 北京 晴 16/3℃)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末掌挚,一起剝皮案震驚了整個濱河市雨席,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吠式,老刑警劉巖陡厘,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異特占,居然都是意外死亡糙置,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門是目,熙熙樓的掌柜王于貴愁眉苦臉地迎上來谤饭,“玉大人,你說我怎么就攤上這事懊纳∪嗟郑” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵嗤疯,是天一觀的道長冤今。 經(jīng)常有香客問我,道長茂缚,這世上最難降的妖魔是什么戏罢? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任屋谭,我火速辦了婚禮,結(jié)果婚禮上龟糕,老公的妹妹穿的比我還像新娘戴而。我一直安慰自己,他們只是感情好翩蘸,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布所意。 她就那樣靜靜地躺著,像睡著了一般催首。 火紅的嫁衣襯著肌膚如雪扶踊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天郎任,我揣著相機(jī)與錄音秧耗,去河邊找鬼。 笑死舶治,一個胖子當(dāng)著我的面吹牛分井,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播霉猛,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼尺锚,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了惜浅?” 一聲冷哼從身側(cè)響起瘫辩,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎坛悉,沒想到半個月后伐厌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡裸影,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年挣轨,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片轩猩。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡卷扮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出界轩,到底是詐尸還是另有隱情画饥,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布浊猾,位于F島的核電站,受9級特大地震影響热鞍,放射性物質(zhì)發(fā)生泄漏葫慎。R本人自食惡果不足惜衔彻,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望偷办。 院中可真熱鬧艰额,春花似錦、人聲如沸椒涯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽废岂。三九已至祖搓,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間湖苞,已是汗流浹背拯欧。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留财骨,地道東北人镐作。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像隆箩,于是被迫代替她去往敵國和親该贾。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容