在WebView加载之前获取advertisingId

时间:2017-11-30 15:41:18

标签: android webview

我有一个WebView,没什么特别的

Map<String, String> headers = new HashMap<String, String>();
headers.put("APP-X-OS", "Android");
headers.put("APP-X-VERSION", BuildConfig.VERSION_NAME);
headers.put("APP-X-DEVICE-ID", Settings.Secure.ANDROID_ID);

webView.loadUrl(
        getString(R.string.app_host_name),
        headers
);

我正在编辑像这样的用户代理

WebSettings webSettings = webView.getSettings();
webSettings.setUserAgentString(
        String.format(
                "%s/%s %s EmbeddedBrowser DeviceUID: %s",
                context.getString(R.string.app_name),
                BuildConfig.VERSION_NAME,
                webSettings.getUserAgentString(),
                Settings.Secure.ANDROID_ID // @TODO AdvertisingID
        )
);

问题是,我的网站正在使用Gemius,直到12月21日,我需要更新我的用户代理,只需将 Settings.Secure.ANDROID_ID 更改为AdvertisingIdClient ID但是问题是

  

此方法无法在主线程中调用,因为它可能阻止导致ANR。如果在主线程上调用了IllegalStateException,则抛出IllegalStateException。

所以我需要在AsyncTask中检索广告ID,我就是这样做的

private class getAdvertisingUid extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... strings) {
        AdvertisingIdClient.Info advertising = null;

        try {
            advertising = AdvertisingIdClient.getAdvertisingIdInfo(
                    getApplicationContext()
            );
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } catch (GooglePlayServicesRepairableException e) {
            e.printStackTrace();
        }

        String uid = null;

        try {
            uid = advertising.getId();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        return uid;
    }

    @Override
    protected void onPostExecute(String uid) {
        advertisingUid = uid;
    }
}

但由于任务是异步的,我在加载WebView和更改UserAgent之后已经获得了广告ID,所以我不能在我的用户代理中使用此ID,但也许仍有可能我不知道?

1 个答案:

答案 0 :(得分:0)

移动整个

WebSettings webSettings = webView.getSettings();
webSettings.setUserAgentString(
        String.format(
                "%s/%s %s EmbeddedBrowser DeviceUID: %s",
                getApplicationContext().getString(R.string.app_name),
                BuildConfig.VERSION_NAME,
                webSettings.getUserAgentString(),
                uid != null ? uid : Settings.Secure.ANDROID_ID
        )
);

onPostExecute 方法,一切正常!如果你依赖于结果,也可以使用这样的东西

asyncTask.execute().get();