7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android Advertising ID を取得する

Posted at

Android広告IDを取得する最小なサンプルコードを作ってみた。
注意すべき点は

  • AdvertisingIdClient.getAdvertisingIdInfo()はメインスレッドから呼ぶとIllegalStateException例外となるので、UIスレッドとは別のスレッドで取得する必要がある。
  • AdvertisingIdClient.Info.isLimitAdTrackingEnabled()の設定に関わらず広告IDは取得できてしまうので、実際に広告IDを使うアプリケーションはisLimitAdTrackingEnabled()の値を考慮した実装とする必要がある。
MainActivity.java
package jp.gr.java_conf.fofn.advertisingid;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "AdvertisingId";

    class AdIdTask extends AsyncTask<Void, Void, String> {
        private Activity mActivity;

        AdIdTask(Activity activity) {
            mActivity = activity;
        }

        @Override
        protected String doInBackground(Void... params) {
            String advertisingId = "";
            try {
                AdvertisingIdClient.Info info =
                        AdvertisingIdClient.getAdvertisingIdInfo(mActivity.getApplicationContext());
                advertisingId = info.getId();
            } catch (GooglePlayServicesNotAvailableException e) {
                Log.e(TAG, "GooglePlayServices not available.");
            } catch (GooglePlayServicesRepairableException e) {
                //
            } catch (IOException e) {
                //
            }
            return advertisingId;
        }

        @Override
        protected void onPostExecute(String id) {
            TextView view = (TextView)mActivity.findViewById(R.id.adid);
            view.append(id);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // AdvertisingIdClient cannot be called in the main thread.
        AsyncTask<Void, Void, String> task = new AdIdTask(this);
        task.execute();
    }
}
7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?