下面列出了怎么用android.net.TrafficStats的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void enter() {
// If we have already started to track time spent in EvaluatingState
// don't reset the timer due simply to, say, commands or events that
// cause us to exit and re-enter EvaluatingState.
if (!mEvaluationTimer.isStarted()) {
mEvaluationTimer.start();
}
sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
if (mUidResponsibleForReeval != INVALID_UID) {
TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
mUidResponsibleForReeval = INVALID_UID;
}
mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
mAttempts = 0;
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
if (BuildConfig.DEBUG) {
//Fix strict mode issue, see https://github.com/square/okhttp/issues/3537#issuecomment-431632176
TrafficStats.setThreadStatsTag(THREAD_ID);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}
@VisibleToAvoidSynthetics
synchronized void updateTotalBytes() {
long currentTotalTxBytes = TrafficStats.getUidTxBytes(UID);
long currentTotalRxBytes = TrafficStats.getUidRxBytes(UID);
if (currentTotalRxBytes == TrafficStats.UNSUPPORTED
|| currentTotalTxBytes == TrafficStats.UNSUPPORTED) {
mIsValid = false;
return;
}
int prefix = mCurrentNetworkType == TYPE_WIFI ? WIFI : MOBILE;
long lastTotalTxBytes = mTotalBytes[TX | MOBILE] + mTotalBytes[TX | WIFI];
long lastTotalRxBytes = mTotalBytes[RX | MOBILE] + mTotalBytes[RX | WIFI];
mTotalBytes[TX | prefix] += currentTotalTxBytes - lastTotalTxBytes;
mTotalBytes[RX | prefix] += currentTotalRxBytes - lastTotalRxBytes;
}
private long getNetSpeed(Context context) {
if (context == null) {
return 0;
}
long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
long nowTimeStamp = System.currentTimeMillis();
long calculationTime = (nowTimeStamp - lastTimeStamp);
if (calculationTime == 0) {
return calculationTime;
}
//毫秒转换
long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / calculationTime);
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
return speed;
}
@Override public ThreadTask call() throws Exception {
isDestroy = false;
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
TrafficStats.setThreadStatsTag(UUID.randomUUID().toString().hashCode());
mAdapter.call(this);
return this;
}
/**
* Test to see if running the given job on the given network is insane.
* <p>
* For example, if a job is trying to send 10MB over a 128Kbps EDGE
* connection, it would take 10.4 minutes, and has no chance of succeeding
* before the job times out, so we'd be insane to try running it.
*/
@SuppressWarnings("unused")
private static boolean isInsane(JobStatus jobStatus, Network network,
NetworkCapabilities capabilities, Constants constants) {
final long estimatedBytes = jobStatus.getEstimatedNetworkBytes();
if (estimatedBytes == JobInfo.NETWORK_BYTES_UNKNOWN) {
// We don't know how large the job is; cross our fingers!
return false;
}
// We don't ask developers to differentiate between upstream/downstream
// in their size estimates, so test against the slowest link direction.
final long slowest = NetworkCapabilities.minBandwidth(
capabilities.getLinkDownstreamBandwidthKbps(),
capabilities.getLinkUpstreamBandwidthKbps());
if (slowest == LINK_BANDWIDTH_UNSPECIFIED) {
// We don't know what the network is like; cross our fingers!
return false;
}
final long estimatedMillis = ((estimatedBytes * DateUtils.SECOND_IN_MILLIS)
/ (slowest * TrafficStats.KB_IN_BYTES / 8));
if (estimatedMillis > JobServiceContext.EXECUTING_TIMESLICE_MILLIS) {
// If we'd never finish before the timeout, we'd be insane!
Slog.w(TAG, "Estimated " + estimatedBytes + " bytes over " + slowest
+ " kbps network would take " + estimatedMillis + "ms; that's insane!");
return true;
} else {
return false;
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
}
byte[] downloadXtraData() {
byte[] result = null;
int startIndex = mNextServerIndex;
if (mXtraServers == null) {
return null;
}
// load balance our requests among the available servers
while (result == null) {
final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_GPS);
try {
result = doDownload(mXtraServers[mNextServerIndex]);
} finally {
TrafficStats.setThreadStatsTag(oldTag);
}
// increment mNextServerIndex and wrap around if necessary
mNextServerIndex++;
if (mNextServerIndex == mXtraServers.length) {
mNextServerIndex = 0;
}
// break if we have tried all the servers
if (mNextServerIndex == startIndex) break;
}
return result;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
}
@Override
public void stop() {
if (running) {
running = false;
trafficTxEnd = TrafficStats.getTotalTxBytes();
trafficRxEnd = TrafficStats.getTotalRxBytes();
}
}
/** @hide */
@VisibleForTesting
public IpSecService(Context context, IpSecServiceConfiguration config) {
this(
context,
config,
(fd, uid) -> {
try {
TrafficStats.setThreadStatsUid(uid);
TrafficStats.tagFileDescriptor(fd);
} finally {
TrafficStats.clearThreadStatsUid();
}
});
}
private static int convertUid(int uid) {
switch (uid) {
case TrafficStats.UID_REMOVED: return UID_REMOVED;
case TrafficStats.UID_TETHERING: return UID_TETHERING;
}
return uid;
}
private void calcDateTraffic(AppTraffic appTraffic, String date, boolean wifi) {
DateTraffic dateTraffic = trafficDbService.getDateTrafficByDate(appTraffic.uid, date);
if (dateTraffic == null) {
dateTraffic = new DateTraffic();
dateTraffic.uid = appTraffic.uid;
dateTraffic.date = date;
dateTraffic.totalRx = 0;
dateTraffic.totalTx = 0;
dateTraffic.mobileRx = 0;
dateTraffic.mobileTx = 0;
dateTraffic.wifiRx = 0;
dateTraffic.wifiTx = 0;
dateTraffic.status = 0;
}
final long rx = TrafficStats.getUidRxBytes(appTraffic.uid);
final long tx = TrafficStats.getUidTxBytes(appTraffic.uid);
final long rxDelta = rx - appTraffic.totalRx;
final long txDelta = tx - appTraffic.totalTx;
dateTraffic.totalRx = dateTraffic.totalRx + rxDelta;
dateTraffic.totalTx = dateTraffic.totalTx + txDelta;
if (!wifi) {
dateTraffic.mobileRx = dateTraffic.mobileRx + rxDelta;
dateTraffic.mobileTx = dateTraffic.mobileTx + txDelta;
} else {
dateTraffic.wifiRx = dateTraffic.wifiRx + rxDelta;
dateTraffic.wifiTx = dateTraffic.wifiTx + txDelta;
}
trafficDbService.saveDateTraffic(dateTraffic);
}
public void run() {
this.prevRxBytes = this.rxBytes;
this.prevTxBytes = this.txBytes;
this.rxBytes = TrafficStats.getTotalRxBytes();
this.txBytes = TrafficStats.getTotalTxBytes();
final long timestamp = System.nanoTime();
this.nsElapsed = timestamp - this.nsTimestamp;
this.nsTimestamp = timestamp;
//double perSecMultiplier = 1000d / msInterval;
this.txTraffic = (nsElapsed > 0 ? (long)((double)(txBytes - prevTxBytes) / (double)(nsElapsed / 1000000000D)) : 0);
this.rxTraffic = (nsElapsed > 0 ? (long)((double)(rxBytes - prevRxBytes) / (double)(nsElapsed / 1000000000D)) : 0);
}
private void update_labels() {
if (totalOn) {
long totalRxBytes = TrafficStats.getTotalRxBytes();
long totalTxBytes = TrafficStats.getTotalTxBytes();
totalTransferTV.setText(String.format("Total:↓%s, ↑%s, ⇅%s", //↑↓▲▼⬆⬇⬍
Formatter.formatFileSize(activity, totalRxBytes),// + "@" + rxRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalTxBytes),// + "@" + txRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalRxBytes + totalTxBytes)// + "@" + totalRate + unitTypeArr[unitType],
));
} else {
long rxRate = totalRxSincePrev * 1000000 / (prevElapsedTime / 1000);
long txRate = totalTxSincePrev * 1000000 / (prevElapsedTime / 1000);
long totalRate = (totalRxSincePrev + totalTxSincePrev) * 1000000 / (prevElapsedTime / 1000);
if (unitType > 3) {
rxRate = (rxRate >> (10 * (unitType - 4)));
txRate = (txRate >> (10 * (unitType - 4)));
totalRate = (totalRate >> (10 * (unitType - 4)));
} else {
rxRate = ((rxRate >> (10 * unitType)) << 3);
txRate = ((txRate >> (10 * unitType)) << 3);
totalRate = ((totalRate >> (10 * unitType)) << 3);
}
totalTransferTV.setText(String.format("Current:↓%s, ↑%s, ⇅%s", //↑↓▲▼⬆⬇⬍
Formatter.formatFileSize(activity, totalRxSincePrev) + "@" + rxRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalTxSincePrev) + "@" + txRate + unitTypeArr[unitType],
Formatter.formatFileSize(activity, totalRxSincePrev + totalTxSincePrev) + "@" + totalRate + unitTypeArr[unitType]
));
}
selectionStatusTV.setText(myChecked.size() + "/" + appStatsList.size());
}
private void getDownloadSpeed() {
long mRxBytesPrevious = TrafficStats.getTotalRxBytes();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long mRxBytesCurrent = TrafficStats.getTotalRxBytes();
long mDownloadSpeed = mRxBytesCurrent - mRxBytesPrevious;
float mDownloadSpeedWithDecimals;
if (mDownloadSpeed >= 1000000000) {
mDownloadSpeedWithDecimals = (float) mDownloadSpeed / (float) 1000000000;
mUnits = " GB";
} else if (mDownloadSpeed >= 1000000) {
mDownloadSpeedWithDecimals = (float) mDownloadSpeed / (float) 1000000;
mUnits = " MB";
} else {
mDownloadSpeedWithDecimals = (float) mDownloadSpeed / (float) 1000;
mUnits = " KB";
}
if (!mUnits.equals(" KB") && mDownloadSpeedWithDecimals < 100) {
mDownloadSpeedOutput = String.format(Locale.US, "%.1f", mDownloadSpeedWithDecimals);
} else {
mDownloadSpeedOutput = Integer.toString((int) mDownloadSpeedWithDecimals);
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
}
public void resetAppTraffic() {
final List<AppTraffic> list = trafficDbService.getAppTrafficList();
AppTraffic appTraffic = null;
for (int i = 0; i < list.size(); i++) {
appTraffic = list.get(i);
appTraffic.totalRx = TrafficStats.getUidRxBytes(appTraffic.uid);
appTraffic.totalTx = TrafficStats.getUidTxBytes(appTraffic.uid);
trafficDbService.saveAppTraffic(appTraffic);
}
}
/**
* Determine how many packets, so far, have been sent (the contents of /proc/net/dev/). This is
* a global value. We use this to determine if any other app anywhere on the phone may have sent
* interfering traffic that might have changed the RRC state without our knowledge.
*
* @return Two values: number of bytes or packets received at index 0, followed by the number
* sent at index 1.
*/
public long[] getPacketsSent() {
long[] retval = {-1, -1};
if (bySize) {
retval[0] = TrafficStats.getMobileRxBytes();
retval[1] = TrafficStats.getMobileTxBytes();
} else {
retval[0] = TrafficStats.getMobileRxPackets();
retval[1] = TrafficStats.getMobileTxPackets();
}
return retval;
}
/**
* {@inheritDoc}
*/
@Override
public long getWiFiRxBytes() throws IOException {
final long l = TrafficStats.getMobileRxBytes();
final long la = TrafficStats.getTotalRxBytes();
if (la < 0L || la < l) {
return 0L;
}
return la - l;
}
public static ApplicationItem create(ApplicationInfo _app){
long _tx = TrafficStats.getUidTxBytes(_app.uid);
long _rx = TrafficStats.getUidRxBytes(_app.uid);
if((_tx + _rx) > 0) return new ApplicationItem(_app);
return null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
/*
* 设置 该线程 的 监测网络的使用情况
* 在 Network Traffic Tool 工具中查到
*/
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
}
public static String getSpeed() {
long totalBytes = TrafficStats.getTotalRxBytes();
if (totalBytes != -1) {
if (mPreviousBytes == 0) {
mPreviousBytes = totalBytes;
} else {
long networkSpeed = TrafficStats.getTotalRxBytes() - mPreviousBytes;
mPreviousBytes = totalBytes;
return getMbString(networkSpeed);
}
}
return "0";
}
private void getFollowing() {
if (BuildConfig.NETWORK_TEST && Build.VERSION.SDK_INT >= 14) {
try {
TrafficStats.setThreadStatsTag(APP_INITIATED_REQUEST);
// Once tag has been applied, network request has to be made request
} finally {
TrafficStats.clearThreadStatsTag();
}
}
RetroInterface.getZomatoRestApi().getUserFollowing(
SessionPreference.getUserId(context) + "",
user_id + "",
new Callback<UserListResponse>() {
@Override
public void success(UserListResponse userListResponse, Response response) {
if (userListResponse != null) {
list = userListResponse.getUsers();
recyclerViewAdapter.refresh(list);
}
}
@Override
public void failure(RetrofitError error) {
}
}
);
}
public void reset() {
startTotalBytes = 0;
lastTotalBytes = TrafficStats.UNSUPPORTED;
lastTotalTxBytes = TrafficStats.UNSUPPORTED;
lastTotalRxBytes = TrafficStats.UNSUPPORTED;
refreshPeriod = 1000;
reqStop = false;
}
private void getRecentlyViewed() {
if (BuildConfig.NETWORK_TEST && Build.VERSION.SDK_INT >= 14) {
try {
TrafficStats.setThreadStatsTag(APP_INITIATED_REQUEST);
// Once tag has been applied, network request has to be made request
} finally {
TrafficStats.clearThreadStatsTag();
}
}
UserLocation location = LocationPreference.getUserLocation(context);
RetroInterface.getZomatoRestApi().getRecentRestaurants(
SessionPreference.getUserId(context) + "",
location.getLatitude() + "",
location.getLongitude() + "",
new Callback<RestaurantResponse>() {
@Override
public void success(RestaurantResponse restaurantResponse, Response response) {
if (restaurantResponse != null && restaurantResponse.isSuccess()) {
allList = restaurantResponse.getItems();
allAdapter.refresh(allList);
}
}
@Override
public void failure(RetrofitError error) {
}
});
}
private void goSocialLogin(User user) {
if (BuildConfig.NETWORK_TEST && Build.VERSION.SDK_INT >= 14) {
try {
TrafficStats.setThreadStatsTag(USER_INITIATED_REQUEST);
// Once tag has been applied, network request has to be made request
} finally {
TrafficStats.clearThreadStatsTag();
}
}
RetroInterface.getZomatoRestApi().loginSocial(
CommonFunctions.getHashMap(user),
new Callback<UserResponse>() {
@Override
public void success(UserResponse userResponse, Response response) {
if (userResponse != null && userResponse.isSuccess()) {
if (userResponse.getUser() != null) {
loginSuccess(userResponse.getUser());
}
}
}
@Override
public void failure(RetrofitError error) {
}
}
);
}