/** * 得到网络速度 * * @param context * @return */ public String getNetSpeed(Context context) { long lastTotalRxBytes = 0; long lastTimeStamp = 0; String netSpeed = "0 kb/s"; long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB; long nowTimeStamp = System.currentTimeMillis(); long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换 lastTimeStamp = nowTimeStamp; lastTotalRxBytes = nowTotalRxBytes; netSpeed = String.valueOf(speed) + " kb/s"; return netSpeed; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_traffic); //��ȡ�ֻ��������� //��ȡ����(R �ֻ�(2G,3G,4G)��������) long mobileRxBytes = TrafficStats.getMobileRxBytes(); //��ȡ�ֻ���������(�ϴ�+����) //T total(�ֻ�(2G,3G,4G)������(�ϴ�+����)) long mobileTxBytes = TrafficStats.getMobileTxBytes(); //total(���������ܺ�(�ֻ�+wifi)) long totalRxBytes = TrafficStats.getTotalRxBytes(); //(������(�ֻ�+wifi),(�ϴ�+����)) long totalTxBytes = TrafficStats.getTotalTxBytes(); //���岻�� //������ȡģ��(���Ͷ���),��Ӫ��(��ͨ,�ƶ�....),(��������)�������ӿ�,��� //����ע�� }
@Override public void run() { double totalBytesReceived = TrafficStats.getUidRxBytes(uid); double totalBytesSent = TrafficStats.getUidTxBytes(uid); if (totalBytesReceived == TrafficStats.UNSUPPORTED || totalBytesSent == TrafficStats.UNSUPPORTED) { Log.w(TAG, "The use of TrafficStats is not supported on this device."); return; } if (previousReceived >= 0 && previousSent >= 0) { received = (totalBytesReceived - previousReceived) / intervalSeconds; sent = (totalBytesSent - previousSent) / intervalSeconds; notifyObservers(); } previousReceived = totalBytesReceived; previousSent = totalBytesSent; handler.postDelayed(this, intervalMilliseconds); }
/** * Creates a section showing some stats from {@link TrafficStats} showing tx/rx bytes and packages * of tagged sockets from boot until now. * * @param uids optional uid to get rx/tx bytes and packages * @return section */ public static Section.HeaderSection createTransferStatSection(int... uids) { Section.ModifiableHeaderSection section = Hood.ext().createSection("Traffic Stats"); if (uids != null) { for (int uid : uids) { section.add(createTxRxdSection("Socket " + uid, TrafficStats.getUidTxBytes(uid), TrafficStats.getUidTxPackets(uid), TrafficStats.getUidRxBytes(uid), TrafficStats.getUidRxPackets(uid))); } } section.add(createTxRxdSection("Mobile", TrafficStats.getMobileTxBytes(), TrafficStats.getMobileTxPackets(), TrafficStats.getMobileRxBytes(), TrafficStats.getMobileRxPackets())); section.add(createTxRxdSection("Total", TrafficStats.getTotalTxBytes(), TrafficStats.getTotalTxPackets(), TrafficStats.getTotalRxBytes(), TrafficStats.getTotalRxPackets())); return section; }
private static List<PageEntry<?>> createTxRxdSection(String name, final long txBytes, final long txPackets, final long rxBytes, final long rxPackets) { List<PageEntry<?>> list = new LinkedList<>(); list.add(Hood.get().createPropertyEntry(name + " TX", new DynamicValue<String>() { @Override public String getValue() { return txBytes == TrafficStats.UNSUPPORTED ? "UNSUPPORTED" : txPackets + " pkt / " + HoodUtil.humanReadableByteCount(txBytes, false); } })); list.add(Hood.get().createPropertyEntry(name + " RCVD", new DynamicValue<String>() { @Override public String getValue() { return rxPackets == TrafficStats.UNSUPPORTED ? "UNSUPPORTED" : rxPackets + " pkt / " + HoodUtil.humanReadableByteCount(rxBytes, false); } })); return list; }
/** * init data */ @Override protected void initData() { long totalRxBytes = TrafficStats.getTotalRxBytes(); long totalTxBytes = TrafficStats.getTotalTxBytes(); long mobileRxBytes = TrafficStats.getMobileRxBytes(); long mobileTxBytes = TrafficStats.getMobileTxBytes(); long totalBytes = totalRxBytes + totalTxBytes; long mobileBytes = mobileRxBytes + mobileTxBytes; tvTotalTrafficStatsSum.setText(getString(R.string.total_traffic_stats_sum, Formatter.formatFileSize(this, totalBytes))); tvMobileTrafficStatsSum.setText(getString(R.string.mobile_traffic_stats_sum, Formatter.formatFileSize(this, mobileBytes))); tvTotalTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, totalTxBytes), Formatter.formatFileSize(this, totalRxBytes))); tvMobileTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, mobileTxBytes), Formatter.formatFileSize(this, mobileRxBytes))); }
public void dataThrougput() { synchronized(this) { totalRxBytes = TrafficStats.getTotalRxBytes(); totalTxBytes = TrafficStats.getTotalTxBytes(); if (dataActivityRunnable.hasDataActivity == 0) { //dataActivityRunnable.initializeHasDataActivity(1); dataActivityRunnable.init(totalRxBytes, totalTxBytes, true); } else if (dataActivityRunnable.hasDataActivity == 1) { //MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onDataActivity", "in sampling"); } else if (dataActivityRunnable.hasDataActivity == 2) { //MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onDataActivity", "already in download"); } } }
/** * This method sends the signal strength update to all listeners of the signal strength update action. * This update includes the absolute signal strength (in dbm) and the percentage it has been assigned. * @param signalStrength */ public void updateSignalStrength(int signalStrength, int nettype, boolean bWifiConnected, int wifiSignal){ Intent intent = new Intent(CommonIntentBundleKeysOld.ACTION_SIGNAL_STRENGTH_UPDATE); intent.putExtra(CommonIntentBundleKeysOld.KEY_UPDATE_SIGNAL_STRENGTH_DBM, signalStrength); intent.putExtra(CommonIntentBundleKeysOld.KEY_UPDATE_NETTYPE, nettype); //if (owner.wsConnected) { long totalRxBytes = TrafficStats.getTotalRxBytes(); long totalTxBytes = TrafficStats.getTotalTxBytes(); intent.putExtra(CommonIntentBundleKeysOld.KEY_RX, totalRxBytes); intent.putExtra(CommonIntentBundleKeysOld.KEY_TX, totalTxBytes); intent.putExtra(CommonIntentBundleKeysOld.KEY_WIFI_CONNECTED, bWifiConnected); intent.putExtra(CommonIntentBundleKeysOld.KEY_WIFI_SIGNAL, wifiSignal); //} owner.sendBroadcast(intent); }
public void updateRxTx () { if (lastRxTxUpdate + 4000 < System.currentTimeMillis()) { // Update Neighbor list history if state changes long rx = TrafficStats.getTotalRxBytes(); long tx = TrafficStats.getTotalTxBytes(); tcpstats.readTcpStats(false); tcpstats.updateCounts(); int tcprsts = tcpstats.tcpResets; int tcperrs = tcpstats.tcpErrors; int tcpretrans = tcpstats.tcpRetrans; if (rx > rxLast + 10000 || tx > txLast + 10000 || tcpstats.tcpResets > tcpstats.prevResets || tcpstats.tcpErrors > tcpstats.prevErrors || tcpstats.tcpRetrans > tcpstats.prevRetrans) { ConnectionSample smp2 = new ConnectionSample(TYPE_RXTX, rx, tx, tcprsts, tcperrs, tcpretrans); rxLast = rx; txLast = tx; connect_history.add(smp2); } lastRxTxUpdate = System.currentTimeMillis(); } }
@Override public boolean handleMessage(Message msg) { //不准?... long mrx = TrafficStats.getMobileRxBytes() / 1024; ////获取通过Mobile连接收到的字节总数,不包含WiFi long mtx = TrafficStats.getMobileTxBytes() / 1024; //Mobile发送的总字节数 long trx = (long) ((TrafficStats.getTotalRxBytes() - mTotalRxBytes) * 1.00f / 1024); mTotalRxBytes = TrafficStats.getTotalRxBytes(); //获取总的接受字节数,包含Mobile和WiFi等 long ttx = TrafficStats.getTotalTxBytes() / 1024; //总的发送字节数,包含Mobile和WiFi等 long uidrx = TrafficStats.getUidRxBytes(getApplicationInfo().uid) / 1024;//获取某个网络UID的接受字节数,某一个进程的总接收量 long uidtx = TrafficStats.getUidTxBytes(getApplicationInfo().uid) / 1024;//获取某个网络UID的发送字节数,某一个进程的总发送量 StringBuilder sb = new StringBuilder(); sb.append("mrx:" + mrx + "\n\r") .append("mtx:" + mtx + "\n\r") .append("trx:" + trx + "\n\r") .append("ttx:" + ttx + "\n\r") .append("uidrx:" + uidrx + "\n\r") .append("uidtx:" + uidtx + "\n\r") ; mTvDeviceInfo.setText(sb.toString()); mHandler.sendEmptyMessageDelayed(0, 1000); return true; }
public final void close() throws IOException { try { super.close(); long l4; long l5; long l6; Object[] arrayOfObject2; return; } finally { long l1 = SystemClock.elapsedRealtime() - NetworkStatsEntity.this.mProcessingStartTime; long l2 = TrafficStats.getUidTxBytes(NetworkStatsEntity.this.mUid); long l3 = TrafficStats.getUidRxBytes(NetworkStatsEntity.this.mUid); Object[] arrayOfObject1 = new Object[5]; arrayOfObject1[0] = NetworkStatsEntity.this.mUa; arrayOfObject1[1] = Long.valueOf(NetworkStatsEntity.this.mResponseLatency); arrayOfObject1[2] = Long.valueOf(l1); arrayOfObject1[3] = Long.valueOf(l2 - NetworkStatsEntity.this.mStartTx); arrayOfObject1[4] = Long.valueOf(l3 - NetworkStatsEntity.this.mStartRx); EventLog.writeEvent(52001, arrayOfObject1); } }
public static HashMap<String, Long> getTraffic() { HashMap<String, Long> hashMap = new HashMap<>(); long mobileRxBytes = TrafficStats.getMobileRxBytes(); long mobileTxBytes = TrafficStats.getMobileTxBytes(); long totalRxBytes = TrafficStats.getTotalRxBytes(); long totalTxbytes = TrafficStats.getTotalTxBytes(); long wifiRxbytes = totalRxBytes - mobileRxBytes; long wifiTxbytes = totalTxbytes - mobileTxBytes; // total traffic hashMap.put("totRxB", totalRxBytes); hashMap.put("totTxB", totalTxbytes); // mobile traffic hashMap.put("mobRxB", mobileRxBytes); hashMap.put("mobTxB", mobileTxBytes); return hashMap; }
/** * Method for polling for the change in total bytes since last update and * adding it to the BandwidthManager. */ protected void addSample() { long newBytes = -1; newBytes = TrafficStats.getUidRxBytes(Process.myUid()); if (newBytes == TrafficStats.UNSUPPORTED) { newBytes = TrafficStats.getTotalRxBytes(); } long byteDiff = newBytes - sPreviousBytes; if (sPreviousBytes >= 0) { synchronized (this) { long curTimeReading = SystemClock.elapsedRealtime(); mConnectionClassManager.addBandwidth(byteDiff, curTimeReading - mLastTimeReading); mLastTimeReading = curTimeReading; } } sPreviousBytes = newBytes; }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } mStartRX = TrafficStats.getUidRxBytes(mUid); mStartTX = TrafficStats.getUidTxBytes(mUid); if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Uh Oh!"); alert.setMessage("Your device does not support traffic stat monitoring."); alert.show(); return; } mUid = android.os.Process.myUid(); }
/** * 获取应用使用的流量 * * @return */ private String getMobleTraffic() { long mobleTraffic = 0L; int uid = getAppUid(); if (uid == -1) { return "0.00M"; } else { mobleTraffic = (TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED) ? 0 : TrafficStats.getUidRxBytes(uid); mobleTraffic += (TrafficStats.getUidTxBytes(uid) == TrafficStats.UNSUPPORTED) ? 0 : TrafficStats.getUidTxBytes(uid); String traffic = mobleTraffic / (float) (1024 * 1024) + "M"; return traffic.substring(0, traffic.indexOf(".") + 3) + "M"; } }
private boolean fetchValues() { stats[0] = TrafficStats.getMobileRxPackets(); if (stats[0] == TrafficStats.UNSUPPORTED) { if (DebugLog.DEBUG) Log.d(TAG, "NetPacketsService.getMetricInfo - mobile rx not supported"); return false; } stats[1] = TrafficStats.getMobileTxPackets(); if (stats[1] == TrafficStats.UNSUPPORTED) { if (DebugLog.DEBUG) Log.d(TAG, "NetPacketsService.getMetricInfo - mobile tx not supported"); return false; } stats[2] = TrafficStats.getTotalRxPackets(); if (stats[2] == TrafficStats.UNSUPPORTED) { if (DebugLog.DEBUG) Log.d(TAG, "NetPacketsService.getMetricInfo - total rx not supported"); return false; } stats[3] = TrafficStats.getTotalTxPackets(); if (stats[3] == TrafficStats.UNSUPPORTED) { if (DebugLog.DEBUG) Log.d(TAG, "NetPacketsService.getMetricInfo - total tx not supported"); return false; } return true; }
@Test public void allQueriesAreStubbed() throws Exception { int anything = -2; assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getThreadStatsTag()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileTxPackets()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileRxPackets()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileTxBytes()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileRxBytes()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalTxPackets()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalRxPackets()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalTxBytes()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalRxBytes()); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTxBytes(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidRxBytes(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTxPackets(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidRxPackets(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpTxBytes(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpRxBytes(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpTxBytes(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpRxBytes(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpTxSegments(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpRxSegments(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpTxPackets(anything)); assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpRxPackets(anything)); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvSupported = (TextView) findViewById(R.id.tvSupported); tvDataUsageWiFi = (TextView) findViewById(R.id.tvDataUsageWiFi); tvDataUsageMobile = (TextView) findViewById(R.id.tvDataUsageMobile); tvDataUsageTotal = (TextView) findViewById(R.id.tvDataUsageTotal); if (TrafficStats.getTotalRxBytes() != TrafficStats.UNSUPPORTED && TrafficStats.getTotalTxBytes() != TrafficStats.UNSUPPORTED) { handler.postDelayed(runnable, 0); initAdapter(); lvApplications = (ListView) findViewById(R.id.lvInstallApplication); lvApplications.setAdapter(adapterApplications); } else { tvSupported.setVisibility(View.VISIBLE); } }
/** * 计算当前流量 * * @param context Context * @param tag traffic tag * @return received bytes */ public static long current(Context context, String tag) { Long appRxValue = sReceivedBytes.get(tag); Long appTxValue = sSendBytes.get(tag); if (appRxValue == null || appTxValue == null) { if (DEBUG) { LogUtils.w(TAG, "current() appRxValue or appTxValue is null."); } return 0; } final int uid = getUid(context); long appRxValue2 = TrafficStats.getUidRxBytes(uid); long appTxValue2 = TrafficStats.getUidTxBytes(uid); long rxValue = appRxValue2 - appRxValue; long txValue = appTxValue2 - appTxValue; if (DEBUG) { LogUtils.v(TAG, "current() rxValue=" + rxValue / 1000 + " txValue=" + txValue / 1000 + " uid=" + uid); } return rxValue; }
/** * 统计TAG流量 * * @param context Context * @param tag traffic tag * @return received bytes */ public static long stop(Context context, String tag) { Long appRxValue = sReceivedBytes.remove(tag); Long appTxValue = sSendBytes.remove(tag); if (appRxValue == null || appTxValue == null) { if (DEBUG) { LogUtils.w(TAG, "stop() appRxValue or appTxValue is null."); } return 0; } final int uid = getUid(context); long appRxValue2 = TrafficStats.getUidRxBytes(uid); long appTxValue2 = TrafficStats.getUidTxBytes(uid); long rxValue = appRxValue2 - appRxValue; long txValue = appTxValue2 - appTxValue; if (DEBUG) { LogUtils.v(TAG, "stop() rxValue=" + rxValue / 1000 + " txValue=" + txValue / 1000 + " uid=" + uid); } return rxValue; }
private void untagQuietly(Socket socket) { if (socket != null) { try { TrafficStats.untagSocket(socket); } catch (SocketException ignored) { } } }
@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()); } }
/** * @param executor The executor used for reading and writing from sockets * @param userExecutor The executor used to dispatch to {@code callback} */ JavaUrlRequest(Callback callback, final Executor executor, Executor userExecutor, String url, String userAgent) { if (url == null) { throw new NullPointerException("URL is required"); } if (callback == null) { throw new NullPointerException("Listener is required"); } if (executor == null) { throw new NullPointerException("Executor is required"); } if (userExecutor == null) { throw new NullPointerException("userExecutor is required"); } this.mCallbackAsync = new AsyncUrlRequestCallback(callback, userExecutor); this.mTrafficStatsTag = TrafficStats.getThreadStatsTag(); this.mExecutor = new Executor() { @Override public void execute(final Runnable command) { executor.execute(new Runnable() { @Override public void run() { int oldTag = TrafficStats.getThreadStatsTag(); TrafficStats.setThreadStatsTag(mTrafficStatsTag); try { command.run(); } finally { TrafficStats.setThreadStatsTag(oldTag); } } }); } }; this.mCurrentUrl = url; this.mUserAgent = userAgent; }
public InterfaceTrafficGatherer() { prevTxBytes = TrafficStats.getTotalTxBytes(); prevRxBytes = TrafficStats.getTotalRxBytes(); txBytes = prevTxBytes; rxBytes = prevRxBytes; nsTimestamp = System.nanoTime(); }
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 setEndTrafficCounter() { if (USE_PROCESS_UID_FOR_TRAFFIC_MEASUREMENT) { this.trafficRxEnd = TrafficStats.getUidRxBytes(processUid); this.trafficTxEnd = TrafficStats.getUidTxBytes(processUid); } else { this.trafficRxEnd = TrafficStats.getTotalRxBytes(); this.trafficTxEnd = TrafficStats.getTotalTxBytes(); } }
@Override public int start() { uid = Process.myUid(); if ((trafficRxStart = TrafficStats.getUidRxBytes(uid)) == TrafficStats.UNSUPPORTED) { return SERVICE_NOT_SUPPORTED; } running = true; trafficTxStart = TrafficStats.getUidTxBytes(uid); return SERVICE_START_OK; }
@Override public void stop() { if (running) { trafficTxEnd = TrafficStats.getUidTxBytes(uid); trafficRxEnd = TrafficStats.getUidRxBytes(uid); } }
@Override public int start() { if ((trafficRxStart = TrafficStats.getTotalRxBytes()) == TrafficStats.UNSUPPORTED) { return SERVICE_NOT_SUPPORTED; } running = true; trafficTxStart = TrafficStats.getTotalTxBytes(); return SERVICE_START_OK; }
@Override public void stop() { if (running) { running = false; trafficTxEnd = TrafficStats.getTotalTxBytes(); trafficRxEnd = TrafficStats.getTotalRxBytes(); } }
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"; }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); out = (TextView) findViewById(R.id.out); stats = new TrafficStats(); }