Java Code Examples for android.net.TrafficStats#getUidTxBytes()

The following examples show how to use android.net.TrafficStats#getUidTxBytes() . 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: StatsTraffic.java    From Cangol-appcore with Apache License 2.0 6 votes vote down vote up
public void calcAppTraffic(String date, boolean wifi) {
    final List<AppTraffic> list = trafficDbService.getAppTrafficList();
    AppTraffic appTraffic = null;
    for (int i = 0; i < list.size(); i++) {
        appTraffic = list.get(i);
        calcDateTraffic(appTraffic, date, wifi);
        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;
        appTraffic.totalRx = rx;
        appTraffic.totalTx = tx;
        if (!wifi) {
            appTraffic.mobileRx = appTraffic.mobileRx + rxDelta;
            appTraffic.mobileTx = appTraffic.mobileTx + txDelta;
        } else {
            appTraffic.wifiRx = appTraffic.wifiRx + rxDelta;
            appTraffic.wifiTx = appTraffic.wifiTx + txDelta;
        }
        trafficDbService.saveAppTraffic(appTraffic);
    }
}
 
Example 2
Source File: DeviceInfoActivty.java    From PracticeDemo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 3
Source File: TrafficUtils.java    From Android-Next with Apache License 2.0 6 votes vote down vote up
/**
 * 统计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;

}
 
Example 4
Source File: WebsiteTestServiceImpl.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
/**
 * 
 */
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();			
	}
}
 
Example 5
Source File: StatsTraffic.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 6
Source File: TrafficSamplerTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Test
public void getUidTxBytes() throws Exception {
    double val = TrafficSampler.getUidTxBytes(2);
    assertEquals(val,101,0);

    PowerMockito.verifyStatic(times(2));
    TrafficStats.getUidTxBytes(2);
}
 
Example 7
Source File: TrafficServiceByUidImpl.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 8
Source File: NetUtil.java    From StickyDecoration with Apache License 2.0 5 votes vote down vote up
/**
 * 流量差(上传)
 * 和上一次获取的时候相比
 *
 * @return
 */
public double getDiffTxBytes() {
    long currentTx = TrafficStats.getUidTxBytes(mUid);
    long diff;
    diff = currentTx - mLastTotalTxBytes;
    mLastTotalTxBytes = currentTx;
    return diff;
}
 
Example 9
Source File: TrafficUtils.java    From Android-Next with Apache License 2.0 5 votes vote down vote up
/**
 * 开始流量统计
 *
 * @param context Context
 * @param tag     traffic tag
 * @return received bytes
 */
public static long start(Context context, String tag) {
    final int uid = getUid(context);
    if (uid > 0) {
        long appRxValue = TrafficStats.getUidRxBytes(uid);
        long appTxValue = TrafficStats.getUidTxBytes(uid);
        sReceivedBytes.put(tag, appRxValue);
        sSendBytes.put(tag, appTxValue);
        if (DEBUG) {
            LogUtils.v(TAG, "start() rxValue=" + appRxValue / 1000 + " txValue=" + appTxValue / 1000 + " uid=" + uid);
        }
        return appRxValue;
    }
    return 0;
}
 
Example 10
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 11
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 12
Source File: Util.java    From Mobilyzer with Apache License 2.0 4 votes vote down vote up
public static long getCurrentRxTxBytes(){
  int uid = android.os.Process.myUid();
  return TrafficStats.getUidRxBytes(uid)+TrafficStats.getUidTxBytes(uid);
}
 
Example 13
Source File: ClementinePlayerConnection.java    From Android-Remote with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Try to connect to Clementine
 *
 * @param message The Request Object. Stores the ip to connect to.
 */
@Override
public boolean createConnection(ClementineMessage message) {
    fireOnConnectionStatusChanged(ConnectionStatus.CONNECTING);

    // Reset the connected flag
    mLastKeepAlive = 0;

    // Now try to connect and set the input and output streams
    boolean connected = super.createConnection(message);

    // Check if Clementine dropped the connection.
    // Is possible when we connect from a public ip and clementine rejects it
    if (connected && !mSocket.isClosed()) {
        // Now we are connected

        // We can now reconnect MAX_RECONNECTS times when
        // we get a keep alive timeout
        mLeftReconnects = MAX_RECONNECTS;

        // Set the current time to last keep alive
        setLastKeepAlive(System.currentTimeMillis());

        // Until we get a new connection request from ui,
        // don't request the first data a second time
        mRequestConnect = ClementineMessageFactory
                .buildConnectMessage(message.getIp(), message.getPort(),
                        message.getMessage().getRequestConnect().getAuthCode(),
                        false,
                        message.getMessage().getRequestConnect().getDownloader());

        // Save started transmitted bytes
        int uid = App.getApp().getApplicationInfo().uid;
        mStartTx = TrafficStats.getUidTxBytes(uid);
        mStartRx = TrafficStats.getUidRxBytes(uid);

        mStartTime = new Date().getTime();

        // Create a new thread for reading data from Clementine.
        // This is done blocking, so we receive the data directly instead of
        // waiting for the handler and still be able to send commands directly.
        mIncomingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isConnected() && !mIncomingThread.isInterrupted()) {
                    checkKeepAlive();

                    ClementineMessage m = getProtoc(3000);
                    if (!m.isErrorMessage() || m.getErrorMessage() != ErrorMessage.TIMEOUT) {
                        Message msg = Message.obtain();
                        msg.obj = m;
                        msg.arg1 = PROCESS_PROTOC;
                        mHandler.sendMessage(msg);
                    }
                }
            }
        });
        mIncomingThread.start();

        // Get hostname
        if (mSocket.getInetAddress() != null) {
            App.Clementine.setHostname(mSocket.getInetAddress().getHostName());
        }

        fireOnConnectionStatusChanged(ConnectionStatus.CONNECTED);

    } else {
        sendUiMessage(new ClementineMessage(ErrorMessage.NO_CONNECTION));
        fireOnConnectionStatusChanged(ConnectionStatus.NO_CONNECTION);
    }

    return connected;
}
 
Example 14
Source File: PreferenceWithRightIcon.java    From Dainty with Apache License 2.0 4 votes vote down vote up
private void getNetFlow(){
    int uid=getPackageUid();
    if(uid!=-1)
        total_flow=TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid);
}
 
Example 15
Source File: DataTrackerFrag.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
private void updateAppList() {

		final List<ApplicationInfo> applications = pk.getInstalledApplications(PackageManager.GET_META_DATA);
		AppStats appStats;

		int i = 0;

		long rx = 0;
		long tx = 0;
//		rxRate = 0;
//		txRate = 0;
		totalRxSincePrev = 0;
		totalTxSincePrev = 0;
		long elapsedRealtimeNanos = 0;
		final LinkedList<AppStats> tempAppStatsList = new LinkedList<>();
		for (ApplicationInfo app : applications) {
            try {
                //appName = app.loadLabel(pk);
                appStats = new AppStats(app.loadLabel(pk), app.packageName, app.uid);

//				if (networkType == 1) {
//					rx = TrafficStats.getUidRxBytes(app.uid);
//					tx = TrafficStats.getUidTxBytes(app.uid);
//				} else if (networkType == 2) {
//					rx = TrafficStats.getUidRxBytes(app.uid);
//					tx = TrafficStats.getUidTxBytes(app.uid);
//				} else if (networkType == 0) {
				rx = TrafficStats.getUidRxBytes(app.uid);
				tx = TrafficStats.getUidTxBytes(app.uid);
				elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();
				//}
				//Log.d(TAG, SystemClock.elapsedRealtimeNanos() + ", " + rx + ", " + tx);
				if ((i = tempOriDataSourceL1.indexOf(appStats)) >= 0) {
					appStats = (AppStats) tempOriDataSourceL1.get(i);

					appStats.elapsedTimeSincePrev = elapsedRealtimeNanos - appStats.elapsedTimeSinceStart;
					appStats.elapsedTimeSinceStart = elapsedRealtimeNanos;

					appStats.bytesRxSincePrev = rx - appStats.bytesRxSinceStart;
					appStats.bytesTxSincePrev = tx - appStats.bytesTxSinceStart;

					appStats.idle = appStats.bytesRxSincePrev == 0 && appStats.bytesTxSincePrev == 0;
					if (!appStats.idle) {
						totalRxSincePrev += appStats.bytesRxSincePrev;
						totalTxSincePrev += appStats.bytesTxSincePrev;
//						rxRate += appStats.bytesRxSincePrev * 1000000 / (appStats.elapsedTimeSincePrev / 1000);
//						txRate += appStats.bytesTxSincePrev * 1000000 / (appStats.elapsedTimeSincePrev / 1000);
						if (statusType != 2) {
							tempAppStatsList.add(appStats);
						}
					} else if (statusType != 1 && (appStats.bytesRxSinceStart > 0 || appStats.bytesTxSinceStart > 0)) {
						tempAppStatsList.add(appStats);
					}
					appStats.bytesRxSinceStart = rx;
					appStats.bytesTxSinceStart = tx;

				} else {
					if (rx > 0 || tx > 0) {
						appStats.idle = false;
						appStats.bytesRxSinceStart = rx;
						appStats.bytesTxSinceStart = tx;

						appStats.bytesRxSincePrev = rx;
						appStats.bytesTxSincePrev = tx;

						totalRxSincePrev += rx;
						totalTxSincePrev += tx;

						if (statusType != 2) {
							tempAppStatsList.add(appStats);
						}
					} 
					tempOriDataSourceL1.add(appStats);

					appStats.elapsedTimeSincePrev = elapsedRealtimeNanos;
					appStats.elapsedTimeSinceStart = elapsedRealtimeNanos;
				}
            } catch (Resources.NotFoundException e) {
            }
        }

		prevElapsedTime = elapsedRealtimeNanos - startTime;
		startTime = elapsedRealtimeNanos;
        Collections.sort(tempAppStatsList, appStatsComparator);
		appStatAdapter.clear();
		appStatAdapter.addAll(tempAppStatsList);

		appStatAdapter.notifyDataSetChanged();
		update_labels();
	}
 
Example 16
Source File: DataTrackerService.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
private void updateAppList() {

		final List<ApplicationInfo> applications = pk.getInstalledApplications(PackageManager.GET_META_DATA);
		AppStats appStats;

		int i = 0;

		long rx = 0;
		long tx = 0;
		totalRxSincePrev = 0;
		totalTxSincePrev = 0;
		long elapsedRealtimeNanos = 0;
		appStatsList.clear();
		for (ApplicationInfo app : applications) {
            try {
                appStats = new AppStats(app.loadLabel(pk), app.packageName, app.uid);

				rx = TrafficStats.getUidRxBytes(app.uid);
				tx = TrafficStats.getUidTxBytes(app.uid);
				elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();

				if ((i = prevAppStatsList.indexOf(appStats)) >= 0) {
					appStats = prevAppStatsList.get(i);

					appStats.elapsedTimeSincePrev = elapsedRealtimeNanos - appStats.elapsedTimeSinceStart;
					appStats.elapsedTimeSinceStart = elapsedRealtimeNanos;

					appStats.bytesRxSincePrev = rx - appStats.bytesRxSinceStart;
					appStats.bytesTxSincePrev = tx - appStats.bytesTxSinceStart;

					appStats.idle = appStats.bytesRxSincePrev == 0 && appStats.bytesTxSincePrev == 0;
					if (!appStats.idle) {
						totalRxSincePrev += appStats.bytesRxSincePrev;
						totalTxSincePrev += appStats.bytesTxSincePrev;
//						rxRate += appStats.bytesRxSincePrev * 1000000 / (appStats.elapsedTimeSincePrev / 1000);
//						txRate += appStats.bytesTxSincePrev * 1000000 / (appStats.elapsedTimeSincePrev / 1000);
						appStatsList.add(appStats);
					} 
					appStats.bytesRxSinceStart = rx;
					appStats.bytesTxSinceStart = tx;

				} else {
					if (rx > 0 || tx > 0) {
						appStats.idle = false;
						appStats.bytesRxSinceStart = rx;
						appStats.bytesTxSinceStart = tx;

						appStats.bytesRxSincePrev = rx;
						appStats.bytesTxSincePrev = tx;

						totalRxSincePrev += rx;
						totalTxSincePrev += tx;

						appStatsList.add(appStats);
					} 
					prevAppStatsList.add(appStats);

					appStats.elapsedTimeSincePrev = elapsedRealtimeNanos;
					appStats.elapsedTimeSinceStart = elapsedRealtimeNanos;
				}
            } catch (Resources.NotFoundException e) {
            }
        }

		prevElapsedTime = elapsedRealtimeNanos - startTime;
		rateTotalRxSincePrev = totalRxSincePrev * 1000000 / (prevElapsedTime / 1000);
		rateTotalTxSincePrev = totalTxSincePrev * 1000000 / (prevElapsedTime / 1000);
		if (unitType > 3) {
			rateTotalRxSincePrev = (rateTotalRxSincePrev >> (10 * (unitType - 4)));
			rateTotalTxSincePrev = (rateTotalTxSincePrev >> (10 * (unitType - 4)));
		} else {
			rateTotalRxSincePrev = ((rateTotalRxSincePrev >> (10 * unitType)) << 3);
			rateTotalTxSincePrev = ((rateTotalTxSincePrev >> (10 * unitType)) << 3);
		}
		startTime = elapsedRealtimeNanos;
	}
 
Example 17
Source File: QPMGetFlowInfoExecutor.java    From QPM with Apache License 2.0 4 votes vote down vote up
private long[] getFlowByAPI(int uid) {
    long flowUpload = TrafficStats.getUidTxBytes(uid);
    long flowDownload = TrafficStats.getUidRxBytes(uid);
    return new long[]{flowUpload, flowDownload};
}
 
Example 18
Source File: NetUtil.java    From StickyDecoration with Apache License 2.0 2 votes vote down vote up
/**
 * 本次所消耗的流量(上传)
 *
 * @return
 */
public double getTotalTxBytes() {
    long currentTx = TrafficStats.getUidTxBytes(mUid);
    return currentTx - mBeginTotalTxBytes;
}
 
Example 19
Source File: AndroidTrafficStats.java    From cronet with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * @return Number of bytes transmitted since device boot that were attributed to caller's UID.
 *         Counts packets across all network interfaces, and always increases monotonically
 *         since device boot. Statistics are measured at the network layer, so they include
 *         both TCP and UDP usage.
 */
@CalledByNative
private static long getCurrentUidTxBytes() {
    long bytes = TrafficStats.getUidTxBytes(Process.myUid());
    return bytes != TrafficStats.UNSUPPORTED ? bytes : TrafficStatsError.ERROR_NOT_SUPPORTED;
}
 
Example 20
Source File: AndroidTrafficStats.java    From 365browser with Apache License 2.0 2 votes vote down vote up
/**
 * @return Number of bytes transmitted since device boot that were attributed to caller's UID.
 *         Counts packets across all network interfaces, and always increases monotonically
 *         since device boot. Statistics are measured at the network layer, so they include
 *         both TCP and UDP usage.
 */
@CalledByNative
private static long getCurrentUidTxBytes() {
    long bytes = TrafficStats.getUidTxBytes(Process.myUid());
    return bytes != TrafficStats.UNSUPPORTED ? bytes : TrafficStatsError.ERROR_NOT_SUPPORTED;
}