我想以编程方式获得用户广告ID。我使用了来自developer site.But的以下代码,它不工作
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (IOException e) {
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesNotAvailableException e) {
// Google Play services is not available entirely.
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String id = adInfo.getId();
final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
如何以编程方式获取用户的广告id ??请帮帮我
发布于 2015-07-22 14:26:13
我可能会迟到,但这可能会对别人有帮助!
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (NullPointerException e){
e.printStackTrace();
}
return advertId;
}
@Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
发布于 2016-04-15 14:44:47
从后台线程获取广告id:
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
String adId = adInfo != null ? adInfo.getId() : null;
// Use the advertising id
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
// Error handling if needed
}
}
});
我添加了null
检查以防止任何崩溃。如果发生异常,Google example implementation代码将使用NullPointerException
崩溃。
发布于 2017-04-13 21:06:12
如果有人有兴趣在Rx-ing时尝试获取AdvertisingId
部件,那么这可能会有所帮助。
private void fetchAndDoSomethingWithAdId() {
Observable.fromCallable(new Callable<String>() {
@Override
public String call() throws Exception {
return AdvertisingIdClient.getAdvertisingIdInfo(context).getId();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
@Override
public void call(String id) {
//do what you want to do with id for e.g using it for tracking
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
}
https://stackoverflow.com/questions/25846108
复制相似问题