在Textview中打印Android广告ID

时间:2015-07-27 19:14:03

标签: java android

问题:   我正在尝试编写一个仅在textview中显示您的广告ID的准系统Android应用程序。我的代码编译得很好,但是当我运行它时,我的textview保持不变(它仍然是" New Text")。

This is a picture of the screen I'm getting on both my AVD and Actual Device

我的代码: 我已经导入了google play服务SDK,并且在MainActivity类中的onCreate方法中使用了以下代码。

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //The textview I am trying to change
    uniqueID = (TextView) findViewById(R.id.special);
    // declarations for included ad plugin 
    adtechView = (AdtechBannerView) findViewById(R.id.ad_container);
    adtechView.getAdConfiguration();

    Context mContext = MainActivity.this.getApplicationContext();

    try {
        //This should be getting the advertising ID

        AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
        String AdId = adInfo.getId();

        //This should change the textview "uniqueID" to the Ad ID
        uniqueID.setText("Your ID is " + AdId);
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (GooglePlayServicesRepairableException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }

我尝试过的事情:

我通过一些相关问题调查了这个问题。多个消息来源称,由于无法访问Google Play服务,代码可能无法正常运行。

我已经尝试在我没有谷歌播放服务的AVD和我的实际设备上运行代码。两者最终都得到了相同的结果。 (textview保持不变)

我已根据此网站编写此代码:https://www.safaribooksonline.com/blog/2014/01/16/advertising-id-android-kitkat/ 它提供了检索Ad-ID的教程。

我也使用了这个堆栈溢出作为指南,但我并没有面对他的代码面临的同样问题: AdvertisingIdClient getAdvertisingIdInfo hangs forever

我做错了什么?非常感谢提前!

1 个答案:

答案 0 :(得分:0)

您无法从主线程获取广告商ID。 https://www.safaribooksonline.com/blog/2014/01/16/advertising-id-android-kitkat/

从上面的代码看,这似乎发生在主线程上。我建议使用AsyncTask。将广告ID放在doInBackground实现中。由于您只能修改主线程上的UI,因此请在onPostExecute实现中设置TextView的文本。

相关问题