I'm attempting to get the google play advertising ID in Unity but it doesn't seem to be working at all.
Here's the code I'm using that I've found in a couple SO's like this one:
AndroidJavaClass up = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = up.GetStatic<AndroidJavaObject> ("currentActivity");
AndroidJavaClass client = new AndroidJavaClass ("com.google.android.gms.ads.identifier.AdvertisingIdClient");
AndroidJavaObject adInfo = client.CallStatic<AndroidJavaObject> ("getAdvertisingIdInfo",currentActivity);
advertisingID = adInfo.Call<string> ("getId").ToString();
using(AndroidJavaClass pluginClass = new AndroidJavaClass("example.com.Toast")) {
if(pluginClass != null) {
toastClass = pluginClass.CallStatic<AndroidJavaObject>("getInstance");
activityContext.Call("runOnUiThread", new AndroidJavaRunnable(() => {
toastClass.Call("toastMessage", advertisingID);
}));
}
}
I have to do this on an actual device and haven't found a good way to actually log anything save a Toast message, which doesn't display anything here. But if I do this (which gets the android device ID) the toast displays just fine.
AndroidJavaClass up = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = up.GetStatic<AndroidJavaObject> ("currentActivity");
AndroidJavaObject contentResolver = currentActivity.Call<AndroidJavaObject> ("getContentResolver");
AndroidJavaClass secure = new AndroidJavaClass ("android.provider.Settings$Secure");
string android_id = secure.CallStatic<string> ("getString", contentResolver, "android_id");
Any idea what I should be doing to get the Google Play Advertising ID?
I've also tried doing it within the jar code itself natively like this:
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(ToastCLass.getInstance().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;
}
@Override
protected void onPostExecute(String advertId) {
Toast.makeText(ToastClass.getInstance().context, advertId, Toast.LENGTH_LONG).show();
}
};
task.execute();
But that just causes an error on my app when it runs (I think because it's trying to run the AsyncTask on the UI thread?). Again hard, as I haven't really found a way to display the logs/errors.
It seems if I run my app on an emulator I can get to a log, which does help with logging out the info.