1 // Copyright 2018 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.net; 6 7 import android.net.TrafficStats; 8 9 import java.lang.reflect.InvocationTargetException; 10 import java.lang.reflect.Method; 11 12 /** 13 * Class to wrap TrafficStats.setThreadStatsUid(int uid) and TrafficStats.clearThreadStatsUid() 14 * which are hidden and so must be accessed via reflection. 15 */ 16 public class ThreadStatsUid { 17 // Reference to TrafficStats.setThreadStatsUid(int uid). 18 private static final Method sSetThreadStatsUid; 19 // Reference to TrafficStats.clearThreadStatsUid(). 20 private static final Method sClearThreadStatsUid; 21 22 // Get reference to TrafficStats.setThreadStatsUid(int uid) and 23 // TrafficStats.clearThreadStatsUid() via reflection. 24 static { 25 try { 26 sSetThreadStatsUid = TrafficStats.class.getMethod("setThreadStatsUid", Integer.TYPE); 27 sClearThreadStatsUid = TrafficStats.class.getMethod("clearThreadStatsUid"); 28 } catch (NoSuchMethodException | SecurityException e) { 29 throw new RuntimeException("Unable to get TrafficStats methods", e); 30 } 31 } 32 33 /** Calls TrafficStats.setThreadStatsUid(uid) */ set(int uid)34 public static void set(int uid) { 35 try { 36 sSetThreadStatsUid.invoke(null, uid); // Pass null for "this" as it's a static method. 37 } catch (IllegalAccessException e) { 38 throw new RuntimeException("TrafficStats.setThreadStatsUid failed", e); 39 } catch (InvocationTargetException e) { 40 throw new RuntimeException("TrafficStats.setThreadStatsUid failed", e); 41 } 42 } 43 44 /** Calls TrafficStats.clearThreadStatsUid() */ clear()45 public static void clear() { 46 try { 47 sClearThreadStatsUid.invoke(null); // Pass null for "this" as it's a static method. 48 } catch (IllegalAccessException e) { 49 throw new RuntimeException("TrafficStats.clearThreadStatsUid failed", e); 50 } catch (InvocationTargetException e) { 51 throw new RuntimeException("TrafficStats.clearThreadStatsUid failed", e); 52 } 53 } 54 } 55