How to get Advertising ID in android programmatically

前端 未结 12 1581
迷失自我
迷失自我 2020-12-08 04:18

I want to get users Advertising ID programmatically.I used the below code from the developer site.But its not working

         Info adInfo = null;
                   


        
12条回答
  •  渐次进展
    2020-12-08 04:51

    With OS validation.

    Call this in an AsyncTask

    /** Retrieve the Android Advertising Id 
         * 
         * The device must be KitKat (4.4)+ 
         * This method must be invoked from a background thread.
         * 
         * */
        public static synchronized String getAdId (Context context) {
    
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
                return null;
            }
    
            AdvertisingIdClient.Info idInfo = null;
            try {
                idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String advertId = null;
            try{
                advertId = idInfo.getId();
            }catch (NullPointerException e){
                e.printStackTrace();
            }
    
            return advertId;
        }
    

提交回复
热议问题