How to get Advertising ID in android programmatically

前端 未结 12 1552
迷失自我
迷失自我 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:31

    The modern way is to use Coroutines in Kotlin, since AsyncTask is now being deprecated for Android. Here is how I did it:

    import com.google.android.gms.ads.identifier.AdvertisingIdClient
    import kotlinx.coroutines.Dispatchers
    import kotlinx.coroutines.withContext
    
    class AdvertisingInfo(val context: Context) {
    
        private val adInfo = AdvertisingIdClient(context.applicationContext)
    
        suspend fun getAdvertisingId(): String =
            withContext(Dispatchers.IO) {
                //Connect with start(), disconnect with finish()
                adInfo.start()
                val adIdInfo = adInfo.info
                adInfo.finish()
                adIdInfo.id
            }
    }
    

    When you are ready to use the advertising ID, you need to call another suspending function:

    suspend fun applyDeviceId(context: Context) {
        val advertisingInfo = AdvertisingInfo(context)
        // Here is the suspending function call, 
        // in this case I'm assigning it to a static object
        MyStaticObject.adId = advertisingInfo.getAdvertisingId()
    }
    
    0 讨论(0)
  • 2020-12-08 04:33

    Make sure you have added play identity services, then you can get advertising id by running a thread like this:

    Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
                    String advertisingId = adInfo != null ? adInfo.getId() : null;
                } catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
                    exception.printStackTrace();
                }
            }
        };
    
        // call thread start for background process
        thread.start();
    
    0 讨论(0)
  • 2020-12-08 04:34

    Using Kotlin & RxJava Observers

    Import in your Gradle file

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

    Import on top of your kotlin source file

    import io.reactivex.Observable
    import com.google.android.gms.ads.identifier.AdvertisingIdClient
    

    Implement a helper function

        private fun fetchAdIdAndThen(onNext : Consumer<String>, onError : Consumer<Throwable>) {
            Observable.fromCallable(Callable<String> {
                AdvertisingIdClient.getAdvertisingIdInfo(context).getId()
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(onNext, onError);
        }
    

    Then

        fetchAdIdAndThen(Consumer<String>() {
            adId ->
            performMyTaskWithADID(activity, 10000, adId);
        }, Consumer<Throwable>() {
            throwable ->
            throwable.printStackTrace();
            performMyTaskWithADID(activity, 10000, "NoADID");
        })
    
    0 讨论(0)
  • 2020-12-08 04:35

    I might be late but this might help someone else!

        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 (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;
            }
    
            @Override
            protected void onPostExecute(String advertId) {
                Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
            }
    
        };
        task.execute();
    
    0 讨论(0)
  • 2020-12-08 04:37

    You need to run your code using Async Task

    try this

    Using the new Android Advertiser id inside an SDK

    0 讨论(0)
  • 2020-12-08 04:47

    Get GAID(Google’s advertising ID)

    1. Download latest Google Play Services SDK.
    2. Import the code and add it as a library project.
    3. Modify AndroidManifest.xml.

    <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    

    4. Enable ProGuard to shrink and obfuscate your code in project.properties this line

     proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
    

    5. Add rules in proguard-project.txt.

         -keep class * extends java.util.ListResourceBundle {
        protected Object[][] getContents();  }
    
     -keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
            public static final *** NULL;      }
    
        -keepnames @com.google.android.gms.common.annotation.KeepName class *
        -keepclassmembernames class * {
            @com.google.android.gms.common.annotation.KeepName *;
        }
    
        -keepnames class * implements android.os.Parcelable {
            public static final ** CREATOR;
        }
    

    6. Call AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()).getId() in a worker thread to get the id in String. as like this

            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 (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String advertId = null;
                try{
                    advertId = idInfo.getId();
                }catch (Exception e){
                    e.printStackTrace();
                }
                return advertId;
            }
            @Override
            protected void onPostExecute(String advertId) {
                Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
            }
        };
        task.execute();
    

    Enjoy!

    or

    https://developervisits.wordpress.com/2016/09/09/android-2/

    0 讨论(0)
提交回复
热议问题