AdvertisingIdClient getAdvertisingIdInfo hangs forever

timba picture timba · Apr 30, 2014 · Viewed 7.3k times · Source

I'm trying to get advertising ID from Google Play services API. Here is a sample code:

...
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
...

public class MyActivity extends Activity {

    @Override
    protected void onStart() {
        super.onStart();
        Thread thr = new Thread(new Runnable() {
            @Override
            public void run() {
            try {
                Context ctx = MyActivity.this.getApplicationContext();
                AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }
        });

        thr.start();
        synchronized (thr) {
            try {
                thr.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

When I'm calling getAdvertisingIdInfo method, application hangs forever (no matter with debugger or not).

I'm using Windows ADT 22.3, Android SDK API 19, Google Play SDK rev. 16, Android 4.4.2 Nexus devices. I'm integrating API as described here: https://developer.android.com/google/play-services/id.html

What could be a reason?

Answer

timba picture timba · May 1, 2014

I found the reason. It shouldn't block onStart() handler because blocked context blocks Play API in ID settings obtaining. Fixed code looks like this:

@Override
protected void onStart() {
    super.onStart();
    Thread thr = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Context ctx = MyActivity.this.getApplicationContext();
                AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);
                finished(adInfo);
            } catch (...) {
                // All exceptions blocks
            }

            finished(null);
        }
    });

    thr.start();
}

private void finished(final AdvertisingIdClient.Info adInfo){
    if(adInfo!=null){
        // In case you need to use adInfo in UI thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // Do some stuff with adInfo
            }
        });
    }
}

It would be helpful if official instructions had such usage comments.