TrafficStats.setThreadStatsTag(USER_INITIATED)TrafficStats.tagSocket(outputSocket)// Transfer data using socketTrafficStats.untagSocket(outputSocket)
Java
TrafficStats.setThreadStatsTag(USER_INITIATED);TrafficStats.tagSocket(outputSocket);// Transfer data using socketTrafficStats.untagSocket(outputSocket);
classIdentifyTransferSpikeTask{@WorkerThreadfunrequest(url:String){TrafficStats.setThreadStatsTag(APP_INITIATED)// Make network request using HttpURLConnection.connect()...TrafficStats.clearThreadStatsTag()}}
Java
publicclassIdentifyTransferSpikeTask{@WorkerThreadpublicvoidrequest(Stringurl){TrafficStats.setThreadStatsTag(APP_INITIATED);// Make network request using HttpURLConnection.connect()...TrafficStats.clearThreadStatsTag();}}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-08-27。"],[],[],null,["The network traffic generated by an app can have a significant impact on the\nbattery life of the device. To optimize that traffic, you need to measure it\nand identify its source. Network requests can come directly from a user action,\nfrom your own app code, or from a server communicating with your app.\n\nThis topic shows you how to monitor and categorize your network traffic, and\nprovides guidance on identifying and resolving issues.\n\nUse the Network Profiler to monitor requests\n\nUse the [Network Profiler](/studio/profile/network-profiler) to track your\napplication's network requests. You can monitor how and when your app transfers\ndata and optimize the underlying code appropriately.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\n**Figure 1.** Tracking network traffic. The network traffic pattern suggests\nthat efficiency could be dramatically improved by prefetching requests or\nbundling uploads.\n\nBy monitoring the frequency of your data transfers and the amount of data\ntransferred during each connection, you can identify areas of your application\nthat can be made more battery-efficient. Generally, you will be looking for\nshort spikes that can be delayed.\n\nTo better identify the cause of transfer spikes, the Traffic Stats API enables\nyou to tag the data transfers occurring from a socket within a given thread\nusing\n[`TrafficStats.setThreadStatsTag()`](/reference/android/net/TrafficStats#setThreadStatsTag(int)).\nCalling this function doesn't automatically tag all traffic for a particular\nthread; the tags have to be applied to the sockets.\n\nOnce the thread tag is set, you can manually tag and untag individual sockets\nusing\n[`TrafficStats.tagSocket()`](/reference/android/net/TrafficStats#tagSocket(java.net.Socket))\nand\n[`TrafficStats.untagSocket()`](/reference/android/net/TrafficStats#untagSocket(java.net.Socket)).\nA tag is also applied if a socket is opened on the thread, or if a server socket\naccepts a connection.\n\nConcurrent access to the same socket by multiple threads will use whatever tag\nthe socket had when the network packets were sent or received (which may be\ndifferent from when the user wrote or read the data, due to buffering and\nretransmits).\n| **Note:** This technique for tagging network traffic from your app depends on how the APIs that you are using access and manage network sockets. Some networking libraries may not allow the [`TrafficStats`](/reference/android/net/TrafficStats) utilities to tag traffic from your app.\n\nFor example, you can define constants to represent different types of network\ntraffic, as shown in the following code sample: \n\nKotlin \n\n```kotlin\nconst val USER_INITIATED = 0x1000\nconst val APP_INITIATED = 0x2000\nconst val SERVER_INITIATED = 0x3000\n```\n\nJava \n\n```java\npublic static final int USER_INITIATED = 0x1000;\npublic static final int APP_INITIATED = 0x2000;\npublic static final int SERVER_INITIATED = 0x3000;\n```\n\nYou can then tag your network requests accordingly: \n\nKotlin \n\n```kotlin\nTrafficStats.setThreadStatsTag(USER_INITIATED)\nTrafficStats.tagSocket(outputSocket)\n// Transfer data using socket\nTrafficStats.untagSocket(outputSocket)\n```\n\nJava \n\n```java\nTrafficStats.setThreadStatsTag(USER_INITIATED);\nTrafficStats.tagSocket(outputSocket);\n// Transfer data using socket\nTrafficStats.untagSocket(outputSocket);\n```\n\nThe [`HttpURLConnection`](/reference/java/net/HttpURLConnection)\nlibrary automatically tags sockets based on the current\n[`TrafficStats.getThreadStatsTag()`](/reference/android/net/TrafficStats#getThreadStatsTag())\nvalue. The library also tags and untags sockets when recycled through\nkeep-alive pools as shown in the following code sample: \n\nKotlin \n\n```kotlin\nclass IdentifyTransferSpikeTask {\n @WorkerThread\n fun request(url: String) {\n TrafficStats.setThreadStatsTag(APP_INITIATED)\n // Make network request using HttpURLConnection.connect()\n ...\n TrafficStats.clearThreadStatsTag()\n }\n}\n```\n\nJava \n\n```java\npublic class IdentifyTransferSpikeTask {\n @WorkerThread\n public void request(String url) {\n TrafficStats.setThreadStatsTag(APP_INITIATED);\n // Make network request using HttpURLConnection.connect()\n ...\n TrafficStats.clearThreadStatsTag();\n }\n}\n```\n| **Note:** When running performance tests, your APK should be as close as possible to the production build. You may want to create a new debuggable build type, separate from the debug build type, in order to achieve this. For more information on creating build types, see [Configure build\n| types](/studio/build/build-variants#build-types).\n\nAnalyze network traffic types\n\nWhen you look at the network traffic generated by your app, you need to\nunderstand the source of the traffic so you can optimize it appropriately.\nFrequent network activity generated by your app may be entirely appropriate\nif it is responding to user actions, but completely inappropriate if your app\nis not in the foreground or if the device is in a pocket or purse.\n\nAnalyze user-initiated traffic\n\nUser-initiated network traffic may be efficiently grouped together while a user\nis performing a specific task within your app, or spread out unevenly as the\nuser requests additional information your app needs to get. Your goal in\nanalyzing user-initiated network traffic is to look for patterns of frequent\nnetwork use over time and attempt to decrease their frequency by grouping\nrequests together.\n\nThe unpredictability of user requests makes it challenging to optimize this\ntype of network use in your app. In addition, users expect fast responses when\nthey are actively using an app, so delaying requests for efficiency can lead to\npoor user experiences. In general, you should prioritize a quick response to\nthe user over efficient use of the network while a user is directly interacting\nwith your app.\n\nFor recommendations to optimize user-initiated traffic, see [Optimize\nuser-initiated\nrequests](/develop/connectivity/minimize-effect-regular-updates#user-initiated).\n| **Caution:** Beware of network activity grouping bias in your user activity test data. If you ran a set of user scenarios with your network testing plan, the graph of user-initiated network access may be unrealistically grouped together, potentially causing you to optimize for user behavior that does not actually occur. Make sure your user network test scenarios reflect realistic use of your app.\n\nAnalyze app-initiated traffic\n\nApp-initiated network traffic is typically an area where you can have a\nsignificant impact on the efficient use of network bandwidth. In analyzing the\nnetwork activity of your app, look for periods of inactivity and determine if\nthey can be increased. If you see patterns of consistent network access from\nyour app, try to batch this traffic to allow the device radio to switch back\ninto low-power mode between periods of activity.\n\nFor recommendations to optimize app-initiated traffic, see [Optimize\napp-initiated\nrequests](/develop/connectivity/minimize-effect-regular-updates#app-initiated).\n\nAnalyze server-initiated traffic\n\nNetwork activity initiated by servers communicating with your app is also\ntypically an area where you can have a significant impact on the efficient use\nof network bandwidth. [Firebase Cloud Messaging\n(FCM)](https://firebase.google.com/docs/cloud-messaging/) is a lightweight\nmechanism used to transmit data from a server to a particular app instance.\nUsing FCM, your server can notify your app running on a particular device that\nthere is new data available for it.\n\nFor recommendations to optimize server-initiated traffic, see [Optimize\nserver-initiated\nrequests](/develop/connectivity/minimize-effect-regular-updates#server-initiated).\n\nUse Battery Historian to visualize network traffic effects\n\n[Battery Historian](/topic/performance/power/battery-historian)\nis a tool that visualizes a device's battery consumption over a period of time.\nYou can use this tool to analyze how your network activity affects battery\nconsumption. For example, Battery Historian can show you whether your app is\nusing the cellular radio more frequently than you expect. For more information\nabout using the Battery Historian, see [Profile battery usage with Batterystats\nand Battery Historian](/topic/performance/power/setup-battery-historian)."]]