jjzjj

android - AdvertisingIdClient getAdvertisingIdInfo 永远挂起

coder 2023-11-22 原文

我正在尝试从 Google Play 服务 API 获取广告 ID。这是一个示例代码:

...
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();
            }
        }
    }
}

当我调用 getAdvertisingIdInfo 方法时,应用程序永远挂起(无论是否使用调试器)。

我使用的是 Windows ADT 22.3、Android SDK API 19、Google Play SDK 修订版。 16、Android 4.4.2 Nexus 设备。我正在按照此处所述集成 API:https://developer.android.com/google/play-services/id.html

可能是什么原因?

最佳答案

我找到了原因。它不应阻止 onStart() 处理程序,因为阻止的上下文会阻止获取 ID 设置中的 Play API。固定代码如下所示:

@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
            }
        });
    }
}

如果官方说明有这样的使用说明会很有帮助。

关于android - AdvertisingIdClient getAdvertisingIdInfo 永远挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23379879/

有关android - AdvertisingIdClient getAdvertisingIdInfo 永远挂起的更多相关文章

随机推荐