AdvertisingIdClient getAdvertisingIdInfo hangs forever

前端 未结 2 1360
清歌不尽
清歌不尽 2021-02-20 03:54

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;
imp         


        
2条回答
  •  温柔的废话
    2021-02-20 04:04

    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.

提交回复
热议问题