如何以编程方式在android中获取广告ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25846108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Advertising ID in android programmatically
提问by user3868543
I want to get users Advertising ID programmatically.I used the below code from the developer site.But its not working
我想以编程方式获取用户广告 ID。我使用了来自开发人员站点的以下代码。但它不起作用
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();
How can I get user's advertising id programmatically ?? please help me
如何以编程方式获取用户的广告 ID?请帮我
回答by DaniZ
I might be late but this might help someone else!
我可能会迟到,但这可能会帮助别人!
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();
回答by Praveen Kumar Verma
Get GAID(Google's advertising ID)
1.Download latest Google Play Services SDK.
2.Import the code and add it as a library project.
3.Modify AndroidManifest.xml.
获取 GAID(Google 的广告 ID)
1.下载最新的 Google Play Services SDK。
2.导入代码并添加为库项目。
3.修改AndroidManifest.xml。
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
4.Enable ProGuard to shrink and obfuscate your code in project.propertiesthis line
4.在project.properties这一行启用 ProGuard 来缩小和混淆你的代码
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
5.Add rules in proguard-project.txt.
5.在proguard-project.txt 中添加规则。
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents(); }
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL; }
-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
@com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
6.Call AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()).getId() in a worker thread to get the id in String. as like this
6.在工作线程中调用 AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()).getId() 以获取 String 中的 id。像这样
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 (Exception e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (Exception e){
e.printStackTrace();
}
return advertId;
}
@Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
Enjoy!
享受!
or
或者
回答by Wahib Ul Haq
Just in case someone is interested in trying out the fetching AdvertisingId
part while Rx-ing then this might be helpful.
以防万一有人有兴趣在AdvertisingId
Rx-ing 时尝试获取部分,那么这可能会有所帮助。
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();
}
});
}
回答by Timo B?hr
Fetch the advertising id from background thread:
从后台线程获取广告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
}
}
});
I added null
checks to prevent any crashes. The Google example implementationcode would crash with a NullPointerException
if an exception occures.
我添加了null
检查以防止任何崩溃。如果发生异常,Google示例实现代码将崩溃NullPointerException
。
回答by htafoya
With OS validation.
带有操作系统验证。
Call this in an AsyncTask
在AsyncTask 中调用它
/** Retrieve the Android Advertising Id
*
* The device must be KitKat (4.4)+
* This method must be invoked from a background thread.
*
* */
public static synchronized String getAdId (Context context) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return null;
}
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
} 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;
}
回答by muskomsoft
You can call the below function in onCreate(Bundle savedInstanceState) of the activity
您可以在活动的 onCreate(Bundle savedInstanceState) 中调用以下函数
and in the logcat search for UIDMY then it will display the id like : I/UIDMY: a1cf5t4e-9eb2-4342-b9dc-10cx1ad1abe1
并在logcat中搜索UIDMY,然后它将显示ID,如:I/UIDMY:a1cf5t4e-9eb2-4342-b9dc-10cx1ad1abe1
void getUIDs()
{
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(SplashScreen.this);
String myId = adInfo != null ? adInfo.getId() : null;
Log.i("UIDMY",myId);
} catch (Exception e) {
Toast toast = Toast.makeText(conext, "error occured ", Toast.LENGTH_SHORT);
toast.setGravity(gravity, 0,0);
toast.show();
}
}
});
}
回答by Meanman
You only need this package: implementation("com.google.android.gms:play-services-ads-identifier:17.0.0") It's not really listed anywhere but it's published on Mavne.
你只需要这个包: implementation("com.google.android.gms:play-services-ads-identifier:17.0.0") 它没有真正在任何地方列出,但它发布在 Mavne 上。
Get Google Services using GoogleApiAvailabilityLight.getInstance
使用 GoogleApiAvailabilityLight.getInstance 获取 Google 服务
回答by user3657232
Make sure you have added play identity services, then you can get advertising id by running a thread like this:
确保您已添加播放身份服务,然后您可以通过运行这样的线程来获取广告 ID:
Thread thread = new Thread() {
@Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
String advertisingId = adInfo != null ? adInfo.getId() : null;
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
exception.printStackTrace();
}
}
};
// call thread start for background process
thread.start();
回答by Heath Kornblum
The modern way is to use Coroutines in Kotlin, since AsyncTask is now being deprecated for Android. Here is how I did it:
现代方法是在 Kotlin 中使用协程,因为 AsyncTask 现在已被 Android 弃用。这是我如何做到的:
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class AdvertisingInfo(val context: Context) {
private val adInfo = AdvertisingIdClient(context.applicationContext)
suspend fun getAdvertisingId(): String =
withContext(Dispatchers.IO) {
//Connect with start(), disconnect with finish()
adInfo.start()
val adIdInfo = adInfo.info
adInfo.finish()
adIdInfo.id
}
}
When you are ready to use the advertising ID, you need to call another suspending function:
当您准备使用广告 ID 时,您需要调用另一个挂起函数:
suspend fun applyDeviceId(context: Context) {
val advertisingInfo = AdvertisingInfo(context)
// Here is the suspending function call,
// in this case I'm assigning it to a static object
MyStaticObject.adId = advertisingInfo.getAdvertisingId()
}
回答by Ali Nadalizadeh
Using Kotlin & RxJava Observers
使用 Kotlin 和 RxJava 观察者
Import in your Gradle file
导入您的 Gradle 文件
implementation 'com.google.android.gms:play-services-ads:15.0.0'
Import on top of your kotlin source file
在您的 kotlin 源文件之上导入
import io.reactivex.Observable
import com.google.android.gms.ads.identifier.AdvertisingIdClient
Implement a helper function
实现辅助功能
private fun fetchAdIdAndThen(onNext : Consumer<String>, onError : Consumer<Throwable>) {
Observable.fromCallable(Callable<String> {
AdvertisingIdClient.getAdvertisingIdInfo(context).getId()
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onNext, onError);
}
Then
然后
fetchAdIdAndThen(Consumer<String>() {
adId ->
performMyTaskWithADID(activity, 10000, adId);
}, Consumer<Throwable>() {
throwable ->
throwable.printStackTrace();
performMyTaskWithADID(activity, 10000, "NoADID");
})