类android.net.TrafficStats源码实例Demo

下面列出了怎么用android.net.TrafficStats的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: android_9.0.0_r45   文件: NetworkMonitor.java
@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;
}
 
源代码4 项目: GSYVideoPlayer   文件: Exo2PlayerManager.java
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;
}
 
源代码5 项目: Aria   文件: ThreadTask.java
@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;
    }
}
 
源代码7 项目: okulus   文件: NetworkDispatcher.java
@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());
    }
}
 
源代码8 项目: android_9.0.0_r45   文件: GpsXtraDownloader.java
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;
}
 
源代码9 项目: CrossBow   文件: NetworkDispatcher.java
@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());
    }
}
 
源代码10 项目: KJFrameForAndroid   文件: NetworkDispatcher.java
@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());
    }
}
 
源代码11 项目: open-rmbt   文件: TrafficServiceImpl.java
@Override
public void stop() {
	if (running) {
		running = false;
		trafficTxEnd = TrafficStats.getTotalTxBytes();
		trafficRxEnd = TrafficStats.getTotalRxBytes();
	}
}
 
源代码12 项目: android_9.0.0_r45   文件: IpSecService.java
/** @hide */
@VisibleForTesting
public IpSecService(Context context, IpSecServiceConfiguration config) {
    this(
            context,
            config,
            (fd, uid) -> {
                try {
                    TrafficStats.setThreadStatsUid(uid);
                    TrafficStats.tagFileDescriptor(fd);
                } finally {
                    TrafficStats.clearThreadStatsUid();
                }
            });
}
 
源代码13 项目: android_9.0.0_r45   文件: NetworkStats.java
private static int convertUid(int uid) {
    switch (uid) {
        case TrafficStats.UID_REMOVED: return UID_REMOVED;
        case TrafficStats.UID_TETHERING: return UID_TETHERING;
    }
    return uid;
}
 
源代码14 项目: Cangol-appcore   文件: StatsTraffic.java
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);
}
 
源代码15 项目: open-rmbt   文件: InterfaceTrafficGatherer.java
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);
}
 
源代码16 项目: PowerFileExplorer   文件: DataTrackerFrag.java
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());
}
 
源代码17 项目: internet-speed-meter   文件: ISMService.java
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);
        }

    }
 
源代码18 项目: DaVinci   文件: NetworkDispatcher.java
@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());
    }
}
 
源代码19 项目: Cangol-appcore   文件: StatsTraffic.java
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);
    }
}
 
源代码20 项目: Mobilyzer   文件: RRCTask.java
/**
 * 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;
}
 
源代码21 项目: callmeter   文件: Device.java
/**
 * {@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;
}
 
源代码22 项目: trafficstats-example   文件: ApplicationItem.java
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;
}
 
源代码23 项目: TitanjumNote   文件: NetworkDispatcher.java
@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());
    }
}
 
源代码24 项目: product-emm   文件: NetworkDispatcher.java
@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());
    }
}
 
源代码25 项目: SaveVolley   文件: NetworkDispatcher.java
@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());
    }
}
 
源代码26 项目: letv   文件: StatisticsUtils.java
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) {

                    }
                }
        );
    }
 
源代码28 项目: NetUpDown   文件: NetTrafficSpider.java
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) {

                    }
                }
        );

    }
 
 类所在包
 同包方法