谷歌广告id返回null



所以我创建了一个类来检索用户设备的Google广告id。然而,我仍然得到一个空指针。我问了这个问题

然而,它仍然没有起作用。这是我的班级代码

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
public class GAID extends AppCompatActivity {
public String mUserId;
public GAID() {
    new Thread(new Runnable() {
        public void run() {
            try {Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
                mUserId = adInfo.getId();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gaid);
}
public String getGAID() {
            return mUserId;
        }

我正在处理同样的问题。我找到了一个解决方案,但并不完美。

//retrieving GIDA
    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) {
            mUserId = advertId;
            collectedGIDA =true;
            Toast.makeText(getApplicationContext(), mUserId , Toast.LENGTH_SHORT).show();
        }
    };
    task.execute();

相关内容

  • 没有找到相关文章

最新更新