我想获取我的应用程序的广告ID,但我没有成功。
import androidx.ads.identifier.AdvertisingIdClient;
import androidx.ads.identifier.AdvertisingIdInfo;
public class addUtilsJava extends AsyncTask<Context, String, String> {
static String TAG = "addUtilsJava";
private String getIdThread(Context context) {
AdvertisingIdInfo adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context).get();
} catch (Exception exception) {
exception.printStackTrace();
}
if (adInfo != null) {
final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
return adInfo.getId();
}
return null;
}
@Override
protected String doInBackground(Context... contexts) {
return getIdThread(contexts[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null)
Log.d(TAG, s);
}
}
它抛出异常,提示我
androidx.ads.identifier.AdvertisingIdNotAvailableException: No Advertising ID Provider available
。我试过2手机和模拟器都具有相同的结果。提前致谢
ps:我检查了android doc中提供的解决方案,但不适用于我https://developer.android.com/training/articles/ad-id
我宁愿有一个不需要依赖的解决方案
最佳答案
试试这个代码..对我的工作..
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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_LONG).show();
}
};
task.execute();
}
}
build.gradle添加了依赖
dependencies {
implementation 'com.google.android.gms:play-services-ads-lite:18.1.1'
}