android.net.TrafficStats Java Examples

The following examples show how to use android.net.TrafficStats. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #2
Source File: Exo2PlayerManager.java    From GSYVideoPlayer with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: NetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: GzipRequestInterceptor.java    From mapbox-events-android with MIT License 6 votes vote down vote up
@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);
}
 
Example #5
Source File: ISMService.java    From internet-speed-meter with MIT License 6 votes vote down vote up
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);
        }

    }
 
Example #6
Source File: TrafficStatsNetworkBytesCollector.java    From Battery-Metrics with MIT License 6 votes vote down vote up
@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;
}
 
Example #7
Source File: TrafficSamplerTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    PowerMockito.mockStatic(TrafficStats.class);
    Mockito.when(TrafficStats.getUidRxBytes(Matchers.anyInt()))
            .thenReturn(100L);

    Mockito.when(TrafficStats.getUidTxBytes(Matchers.anyInt()))
            .thenReturn(101L);
}
 
Example #8
Source File: RecentPlaceActivity.java    From Expert-Android-Programming with MIT License 5 votes vote down vote up
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) {

                    }
                });

    }
 
Example #9
Source File: Device.java    From callmeter with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public long getCellTxBytes() throws IOException {
    final long l = TrafficStats.getMobileTxBytes();
    if (l < 0L) {
        return 0L;
    }
    return l;
}
 
Example #10
Source File: NetworkDispatcher.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #11
Source File: NetworkDispatcher.java    From device-database with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #12
Source File: InterfaceTrafficGatherer.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
public InterfaceTrafficGatherer() {
	prevTxBytes = TrafficStats.getTotalTxBytes();
	prevRxBytes = TrafficStats.getTotalRxBytes();
	txBytes = prevTxBytes;
	rxBytes = prevRxBytes;
	nsTimestamp = System.nanoTime();
}
 
Example #13
Source File: BrowseNearbyActivity.java    From Expert-Android-Programming with MIT License 5 votes vote down vote up
private void getRestaurants() {

        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().getRecommendedRestaurants(
                SessionPreference.getUserId(context)+"",
                location.getLatitude() + "",
                location.getLongitude() + "",
                new Callback<RestaurantResponse>() {
                    @Override
                    public void success(RestaurantResponse restaurantResponse, Response response) {

                        if (restaurantResponse != null && restaurantResponse.isSuccess()) {
                            mightList = restaurantResponse.getItems();
                            mightAdapter.refresh(mightList);
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {

                    }
                }
        );
    }
 
Example #14
Source File: SignInBaseActivity.java    From Expert-Android-Programming with MIT License 5 votes vote down vote up
private void goNormalRegister(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().registerNormal(
                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) {

                    }
                }
        );

    }
 
Example #15
Source File: NetworkDispatcher.java    From pearl with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(com.hanuor.pearl.volleysingleton.Request<?> request) {
    // Tag the request (if API >= 14)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
    }
}
 
Example #16
Source File: FindFriendActivity.java    From Expert-Android-Programming with MIT License 5 votes vote down vote up
private void followUser(int pos, boolean isFollowing) {

        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();
            }
        }

        User user = allList.get(pos);
        RetroInterface.getZomatoRestApi().followUser(
                SessionPreference.getUserId(context) + "",
                user.getId() + "",
                (isFollowing ? 1 : 0) + "",
                new Callback<NormalResponse>() {
                    @Override
                    public void success(NormalResponse userListResponse, Response response) {

                    }

                    @Override
                    public void failure(RetrofitError error) {

                    }
                }
        );
    }
 
Example #17
Source File: GoJsActivity.java    From DragonGoApp with GNU Affero General Public License v3.0 5 votes vote down vote up
public void updateTraffic() {
	long newrx = TrafficStats.getTotalRxBytes();
	long newtx = TrafficStats.getTotalTxBytes();
	if (rx!=newrx||tx!=newtx) {
		rx=newrx; tx=newtx;
		writeTraffix(rx+tx);
	}
}
 
Example #18
Source File: NetworkDispatcher.java    From FeedListViewDemo with MIT License 5 votes vote down vote up
@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());
    }
}
 
Example #19
Source File: ThreadTask.java    From Aria with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #20
Source File: ModSmartRadio.java    From GravityBox with Apache License 2.0 5 votes vote down vote up
private boolean shouldPostponeAlarm() {
    boolean postpone = false;
    if (mAdaptiveDelayThreshold > 0) {
        // if there's link activity higher than defined threshold
        long rxDelta = TrafficStats.getMobileRxBytes() - mLinkActivity.rxBytes;
        long txDelta = TrafficStats.getMobileTxBytes() - mLinkActivity.txBytes;
        long timeDelta = System.currentTimeMillis() - mLinkActivity.timestamp;
        long speedRxKBs = (long)(rxDelta / (timeDelta / 1000f)) / 1024;
        long speedTxKBs = (long)(txDelta / (timeDelta / 1000f)) / 1024;
        postpone |= speedTxKBs >= mAdaptiveDelayThreshold || speedRxKBs >= mAdaptiveDelayThreshold;
        if (DEBUG) log("shouldPostponeAlarm: speedRxKBs=" + speedRxKBs +
                "; speedTxKBs=" + speedTxKBs + "; threshold=" + mAdaptiveDelayThreshold);
    }
    return postpone;
}
 
Example #21
Source File: SignInBaseActivity.java    From Expert-Android-Programming with MIT License 5 votes vote down vote up
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) {

                    }
                }
        );

    }
 
Example #22
Source File: LaunchApp.java    From PUMA with Apache License 2.0 5 votes vote down vote up
private void waitForNetworkUpdate(long idleTimeoutMillis, long globalTimeoutMillis) {
	final long startTimeMillis = SystemClock.uptimeMillis();
	long prevTraffic = TrafficStats.getUidTxBytes(uid) + TrafficStats.getUidRxBytes(uid);
	boolean idleDetected = false;
	long totTraffic = 0;

	while (!idleDetected) {
		final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
		final long remainingTimeMillis = globalTimeoutMillis - elapsedTimeMillis;
		if (remainingTimeMillis <= 0) {
			Util.err("NO_IDLE_TIMEOUT: " + globalTimeoutMillis);
			break;
		}

		try {
			Thread.sleep(idleTimeoutMillis);
			long currTraffic = TrafficStats.getUidTxBytes(uid) + TrafficStats.getUidRxBytes(uid);
			long delta = currTraffic - prevTraffic;
			if (delta > 0) {
				totTraffic += delta;
				prevTraffic = currTraffic;
			} else { // idle detected
				idleDetected = true;
			}
		} catch (InterruptedException ie) {
			/* ignore */
		}
	}

	if (idleDetected) {
		Util.log("Traffic: " + totTraffic);
	}
}
 
Example #23
Source File: NetTrafficSpider.java    From NetUpDown with Apache License 2.0 5 votes vote down vote up
public void reset() {
    startTotalBytes = 0;
    lastTotalBytes = TrafficStats.UNSUPPORTED;
    lastTotalTxBytes = TrafficStats.UNSUPPORTED;
    lastTotalRxBytes = TrafficStats.UNSUPPORTED;
    refreshPeriod = 1000;
    reqStop = false;
}
 
Example #24
Source File: FollowingFragment.java    From Expert-Android-Programming with MIT License 5 votes vote down vote up
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) {

                    }
                }
        );
    }
 
Example #25
Source File: StatisticsUtils.java    From letv with Apache License 2.0 5 votes vote down vote up
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";
}
 
Example #26
Source File: NetworkDispatcher.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #27
Source File: NetworkDispatcher.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #28
Source File: NetworkDispatcher.java    From TitanjumNote with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #29
Source File: ApplicationItem.java    From trafficstats-example with MIT License 5 votes vote down vote up
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;
}
 
Example #30
Source File: Device.java    From callmeter with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@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;
}