【问题标题】:AdvertisingIdClient getAdvertisingIdInfo blocked by main threadAdvertisingIdClient getAdvertisingIdInfo 被主线程阻止
【发布时间】:2015-01-15 10:43:59
【问题描述】:

我正在尝试等待 AdvertisingIdClient.getAdvertisingIdInfo(activity) 的响应,但没有成功。在主线程完成之前,此方法永远不会响应。

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.io.IOException;


public class MyActivity extends Activity {

    private Activity m_activity = null;
    private AdvertisingIdClient.Info m_info = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // start the thread with the getAdvertisingIdInfo()
        startGoogleAdvertisingIdRequest(this);

        // simulate a waiting loop, others app init, ...
        for (int i=0; i<20; i++) {
            SystemClock.sleep(100);
        }

        // get the uuid
        String uuid = getGoogleAdvertisingId();

        // call a method who need the uuid
        Log.i("UUID", "receive uuid: " + uuid);
    }


    public String getGoogleAdvertisingId() {
        String uuid = null;
        if (m_info != null) {
            if (!m_info.isLimitAdTrackingEnabled()) {
                uuid = m_info.getId();
            } else {
                uuid = "another uuid";
            }
        } else {
            uuid = "another uuid";
        }

        return uuid;
    }

    public void startGoogleAdvertisingIdRequest(final Activity activity) {
        m_activity = activity;
        if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity) == ConnectionResult.SUCCESS) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    AdvertisingIdClient.Info adInfo = null;
                    try {
                        Log.i("UUID", "before google request");
                        adInfo = AdvertisingIdClient.getAdvertisingIdInfo(activity);
                        Log.i("UUID", "after google request");
                    } catch (IOException e) {
                        Log.w("UUID", "getAdvertisingIdInfo IOException: " + e.getMessage());
                    } catch (GooglePlayServicesNotAvailableException e) {
                        Log.w("UUID", "GooglePlayServicesNotAvailableException: " + e.getMessage());
                    } catch (Exception e) {
                        Log.w("UUID", "GooglePlayServicesException: " + e.getMessage());
                    } finally {
                        finished(adInfo);
                    }
                }
            }).start();
        }
    }

    private void finished(final AdvertisingIdClient.Info adInfo){
        if(adInfo != null){
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    m_info = adInfo;
                    Log.i("UUID", "runOnUiThread id: " + adInfo.getId());
                }
            });
        }
    }
}

这段代码的Logcat

11:29:52.103  30810-30828/com.example.testuuid I/UUID﹕ before google request
11:29:54.107  30810-30810/com.example.testuuid I/UUID﹕ receive uuid: another uuid
11:29:54.127  30810-30828/com.example.testuuid I/UUID﹕ after google request
11:29:54.151  30810-30810/com.example.testuuid I/UUID﹕ runOnUiThread id: d5dc3bfb-4756-490c-8f8e-2bedfb5e827a

相同的 logcat 等待时间更长(5 秒)

11:36:14.215  31413-31436/com.example.testuuid I/UUID﹕ before google request
11:36:19.225  31413-31413/com.example.testuuid I/UUID﹕ receive uuid: another uuid
11:36:19.293  31413-31436/com.example.testuuid I/UUID﹕ after google request
11:36:19.315  31413-31413/com.example.testuuid I/UUID﹕ runOnUiThread id: d5dc3bfb-4756-490c-8f8e-2bedfb5e827a

每次getAdvertisingIdInfo(),在另一个线程中,都会被主线程阻塞。

是什么原因?以及如何做到这一点?

【问题讨论】:

  • 你考虑过使用AsyncTask吗?
  • @Fildor:是的,我试试AsyncTask,问题是一样的。
  • 那么我的猜测是m_info.getId(); 正在阻塞。
  • m_info.getId() 未在此处调用(回退到“另一个 uuid”,因为 m_info 为空,因为响应来得太晚了)。
  • 您是否尝试过将对 isGooglePlayServicesAvailable 的调用放入线程中?

标签: java android multithreading google-play-services


【解决方案1】:

要获取 google 广告 ID,您无需在主线程上运行方法 getAdvertisingIdInfo。 我使用 Async Task 来管理 Google 广告 ID 的提取。

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
String GAID; // this is the String of the Google Ad ID that you'll receive upon onPostExecute

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new GetGAIDTask().execute();
}

private class GetGAIDTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... strings) {
        AdvertisingIdClient.Info adInfo;
        adInfo = null;
            try {
                adInfo = AdvertisingIdClient.getAdvertisingIdInfo(MainActivity.this.getApplicationContext());
                if (adInfo.isLimitAdTrackingEnabled()) // check if user has opted out of tracking
                    return "did not found GAID... sorry";
            } catch (IOException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            }
        return adInfo.getId();
    }

    @Override
    protected void onPostExecute(String s) {
        GAID = s;
    }
}

你还需要添加到app build.gradle上的dependencies这一行

compile 'com.google.android.gms:play-services-ads:7.8.0'

并确保您在 Android SDK 管理器上更新了“EXTRAS Google Repository”

【讨论】:

    【解决方案2】:

    您看到的问题(似乎没有足够长的时间来完成 getAdvertisingIdInfo 调用)是由您的等待方式和 runOnUiThread 的工作方式引起的。关键是 runOnUiThread 会将要在 ui 线程上当前运行的代码(在本例中为 onCreate)之后运行的代码排队。用于“模拟等待”的 sleep 调用将让您的后台线程运行并完成其工作,但设置 m_info 的最终操作将始终在 onCreate 完成后排队并执行。

    一种解决方案是确保 m_info 可以安全地从多个线程访问,并简单地将其分配给后台线程。不需要runOnUiThread。这将消除排队,并允许您的代码以最少的更改工作。

    更好的解决方案是继续使用 runOnUiThread 并删除用于等待的睡眠。您需要记住,m_info 在 onCreate 中将始终为 null,但其他事件可以检查该值是否为非 null 并根据需要使用它。

    https://developer.android.com/reference/android/app/Activity#runOnUiThread(java.lang.Runnable)

    在 UI 线程上运行指定的操作。如果当前线程是 UI 线程,则立即执行该操作。如果当前线程不是UI线程,则将动作发布到UI线程的事件队列中。

    【讨论】:

      【解决方案3】:

      在有关 AdvertisingIdClient 的文献中,它说不要在主线程上使用。它会抛出异常。所以如果你把它放到它自己的线程中你会没事的,很可能。

      AdvertisingIdClient reference

      【讨论】:

        【解决方案4】:

        根据文档 (here):

        不幸的是,在这些情况下使用 com.google.android.gms.iid InstanceID API 或用于创建应用范围 ID 的系统函数不是 适当的解决方案,因为 ID 可能需要跨 应用。另一种解决方案是使用广告标识符 通过 getId() 可从 AdvertisingIdClient.Info 类获得 方法。您可以使用以下方法创建 AdvertisingIdClient.Info 对象 getAdvertisingIdInfo(Context) 方法并调用 getId() 方法 使用标识符。请注意,此方法是阻塞的,因此您应该 不要从主线程调用它;对此的详细解释 方法在这里可用。

        还有here:

        公共静态 AdvertisingIdClient.Info getAdvertisingIdInfo (上下文 上下文)

        检索用户的广告 ID 并限制广告跟踪偏好。

        这个方法不能在主线程中调用,因为它可能会阻塞 导致 ANR。如果是这样,将抛出 IllegalStateException 在主线程上调用。

        所以他们说它是阻塞的...... 您需要将此代码放在后台线程中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-04
          • 1970-01-01
          • 2016-11-29
          • 2014-07-12
          相关资源
          最近更新 更多