我在我的应用程序中使用广告ID,代码工作正常,我在运行Android Nougat 7.1.2的设备上测试了它。你能指出我应该添加什么才能在Nougat中获得它?
private static void getAdvertisingID() {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(_context);
if (idInfo.isLimitAdTrackingEnabled()){ // check if user has opted out of tracking
Log.i("NetworkStateChangeReceiver","Not Found");
return "did not found GAID... sorry";
}
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (Exception e){
e.printStackTrace();
}
return advertId;
}
@Override
protected void onPostExecute(String advertId) {
Log.i("NetworkStateChangeReceiver","Found "+advertId);
UtilHelper.setDeviceIDFA(advertId);
}
};
task.execute();
}
答案 0 :(得分:1)
原来代码工作正常,唯一的问题是在Nougat上需要一些调用onPostExecute
方法,而在运行较低android版本的其他设备上,这个方法被快速调用。我刚刚在调用getAdvertisingID
之后添加了一些延迟来获取广告ID,一切都很顺利。
快乐的编码