I'm trying to figure out specifically how much of my app's data use is being used by the requests I send with OkHttpClient, and I saw that I can use TrafficStats to tag a thread and then see it's network activity with the tag.
if I do something like
TrafficStats.setThreadStatsTag(1234);
okHttpClient.execute(request);
then it actually tags it okay(ish), but then when I use the async method (okHttpClient.enqueue(request)
) it doesn't (which is kinda obvious though I hoped they'd have support for that).
So I tried a couple of things:
Any ideas?
I think TrafficStats.setThreadStatsTag() is for thread, so maybe we can add an interceptor for okhttp client.
private static class TrafficStatInterceptor implements Interceptor {
private int trafficTag;
TrafficStatInterceptor(int trafficTag) {
this.trafficTag = trafficTag;
}
@Override
public Response intercept(Chain chain) throws IOException {
if (trafficTag > 0) {
TrafficStats.setThreadStatsTag(trafficTag);
} else {
Log.w(TAG, "invalid traffic tag " + trafficTag);
}
return chain.proceed(chain.request());
}
}
then just add this interceptor
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addNetworkInterceptor(new TrafficStatInterceptor(trafficTag));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With