我正在尝试从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 rev。 16,Android 4.4.2 Nexus设备。我正在按照此处所述集成API:https://developer.android.com/google/play-services/id.html
可能是什么原因?
答案 0 :(得分:11)
我找到了原因。它不应该阻止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
}
});
}
}
如果官方说明有这样的使用意见,将会有所帮助。