Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - OkHttp - Tagging all network requests with TrafficStats

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:

  • Setting a dispatcher for the client where it's a normal dispatcher which basically on every execute replaces the Runnable it receives with a new runnable that first tags the thread an then runs the original runnable - some traffic was tagged but a lot wasn't.
  • Setting a socket factory which basically tags every socket it produces - still some some traffic tagged but most of it wasn't.

Any ideas?

like image 268
dog Avatar asked Sep 06 '25 19:09

dog


1 Answers

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));
like image 137
Tinker Sun Avatar answered Sep 09 '25 18:09

Tinker Sun