Example usage for android.net TrafficStats getTotalRxBytes

List of usage examples for android.net TrafficStats getTotalRxBytes

Introduction

In this page you can find the example usage for android.net TrafficStats getTotalRxBytes.

Prototype

public static long getTotalRxBytes() 

Source Link

Document

Return number of bytes received since device boot.

Usage

From source file:Main.java

public static String getAllTraffic() {
    long traffic = TrafficStats.getTotalRxBytes();
    return byteToM(traffic) + "M";
}

From source file:Main.java

public static float getSysNetworkDownloadSpeed() {
    long nowMS = System.currentTimeMillis();
    long nowBytes = TrafficStats.getTotalRxBytes();

    long timeinterval = nowMS - m_lSysNetworkSpeedLastTs;
    long bytes = nowBytes - m_lSystNetworkLastBytes;

    if (timeinterval > 0)
        m_fSysNetowrkLastSpeed = (float) bytes * 1.0f / (float) timeinterval;

    m_lSysNetworkSpeedLastTs = nowMS;//w w w.  j  a v  a2s  . co  m
    m_lSystNetworkLastBytes = nowBytes;

    return m_fSysNetowrkLastSpeed;
}

From source file:Main.java

public static long getNetRxTotalBytes() {
    long total = TrafficStats.getTotalRxBytes();
    return total;
}

From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java

private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException {
    mCancelable = false;//from www.  ja v  a  2 s .c o m

    if (!SafeSlinger.getApplication().isOnline()) {
        throw new ExchangeException(mCtx.getString(R.string.error_CorrectYourInternetConnection));
    }

    // sets up parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    if (mHttpClient == null) {
        mHttpClient = new CheckedHttpClient(params, mCtx);
    }
    HttpPost httppost = new HttpPost(uri);
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    byte[] reqData = null;
    HttpResponse response = null;
    long startTime = SystemClock.elapsedRealtime();
    int statCode = 0;
    String statMsg = "";
    String error = "";

    try {
        // Execute HTTP Post Request
        httppost.addHeader("Content-Type", "application/octet-stream");
        httppost.setEntity(new ByteArrayEntity(requestBody));

        mTxTotalBytes = requestBody.length;

        final long totalTxBytes = TrafficStats.getTotalTxBytes();
        final long totalRxBytes = TrafficStats.getTotalRxBytes();
        if (totalTxBytes != TrafficStats.UNSUPPORTED) {
            mTxStartBytes = totalTxBytes;
        }
        if (totalRxBytes != TrafficStats.UNSUPPORTED) {
            mRxStartBytes = totalRxBytes;
        }
        response = mHttpClient.execute(httppost);
        reqData = responseHandler.handleResponse(response).getBytes("8859_1");

    } catch (UnsupportedEncodingException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (HttpResponseException e) {
        // this subclass of java.io.IOException contains useful data for
        // users, do not swallow, handle properly
        statCode = e.getStatusCode();
        statMsg = e.getLocalizedMessage();
        error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'");
    } catch (java.io.IOException e) {
        // just show a simple Internet connection error, so as not to
        // confuse users
        error = mCtx.getString(R.string.error_CorrectYourInternetConnection);
    } catch (RuntimeException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (OutOfMemoryError e) {
        error = mCtx.getString(R.string.error_OutOfMemoryError);
    } finally {
        long msDelta = SystemClock.elapsedRealtime() - startTime;
        if (response != null) {
            StatusLine status = response.getStatusLine();
            if (status != null) {
                statCode = status.getStatusCode();
                statMsg = status.getReasonPhrase();
            }
        }
        MyLog.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0)
                + "b recv, " + statCode + " code, " + msDelta + "ms");
    }

    if (!TextUtils.isEmpty(error) || reqData == null) {
        throw new ExchangeException(error);
    }
    return reqData;
}

From source file:org.restcomm.app.utillib.DataObjects.EventObj.java

public EventObj(EventType eventType, long eventTimestamp, long duration, Uri uri, Runnable onUnstage) {
    this.eventType = eventType;
    this.eventTimestamp = eventTimestamp;
    this.duration = duration;
    this.uri = uri;
    this.stageTimestamp = -1L;
    this.onUnstage = onUnstage;
    this.isUploaded = false;
    this.rx = TrafficStats.getTotalRxBytes();
    this.tx = TrafficStats.getTotalTxBytes();
    this.tcpstats = new TcpStats();
    this.tcpstats.readTcpStats(true);
}

From source file:org.restcomm.app.qoslib.Services.LibPhoneStateListener.java

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");
        }/*  w w w . j a v a2s  .  co m*/
    }
}

From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java

public long get_rxCurrentBytes() {
    final long totalRxBytes = TrafficStats.getTotalRxBytes();
    if (totalRxBytes != TrafficStats.UNSUPPORTED) {
        mRxCurrentBytes = totalRxBytes - mRxStartBytes;
    } else {//from   ww  w  .j a  v  a  2 s  . c  o  m
        mRxCurrentBytes = 0;
    }
    return mRxCurrentBytes;
}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

@SuppressLint("DefaultLocale")
private void updateConsole() {

    if (mSystemViews.isEmpty())
        return;/*  w ww  .j av  a  2s  . c o m*/

    try {
        // ----- System -----
        int threadCount = Thread.activeCount();
        ApplicationInfo appInfo = getActivity().getApplicationInfo();

        mSystemViews.get(SYSTEM_PACKAGE).get(1).setText(appInfo.packageName);
        mSystemViews.get(SYSTEM_MODEL).get(1).setText(Build.MODEL);
        mSystemViews.get(SYSTEM_ANDROID).get(1).setText(Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT >= 16) {
            int lines = 0;
            final StringBuilder permSb = new StringBuilder();
            try {
                PackageInfo pi = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(),
                        PackageManager.GET_PERMISSIONS);
                for (int i = 0; i < pi.requestedPermissions.length; i++) {
                    if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
                        permSb.append(pi.requestedPermissions[i]).append("\n");
                        lines++;
                    }
                }
            } catch (Exception e) {
            }
            final int lineCnt = lines;
            mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms [press]", lines));
            mSystemViews.get(SYSTEM_PERM).get(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        String permStr = permSb.toString().replaceAll("android.permission.", "")
                                .replaceAll("\n[^\n]*permission", "");
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(lineCnt);
                    } else {
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms", lineCnt));
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(null);
                    }
                }
            });

        } else {
            String permStr = "";
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Find Loc");
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Coarse Loc");
            mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
        }

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        int processCnt = actMgr.getRunningAppProcesses().size();
        mSystemViews.get(SYSTEM_PROCESSES).get(1).setText(String.format("%d", consoleState.processCnt));
        mSystemViews.get(SYSTEM_PROCESSES).get(2).setText(String.format("%d", processCnt));
        // mSystemViews.get(SYSTEM_BATTERY).get(1).setText(String.format("%d%%", consoleState.batteryLevel));
        mSystemViews.get(SYSTEM_BATTERY).get(2)
                .setText(String.format("%%%d", calculateBatteryLevel(getActivity())));
        // long cpuNano = Debug.threadCpuTimeNanos();
        // mSystemViews.get(SYSTEM_CPU).get(2).setText(String.format("%d%%", cpuNano));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        // ----- Network WiFi-----

        WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
            mNetworkViews.get(NETWORK_WIFI_IP).get(1).setText(Formatter.formatIpAddress(dhcpInfo.ipAddress));
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            mNetworkViews.get(NETWORK_WIFI_SPEED).get(1).setText(String.valueOf(wifiInfo.getLinkSpeed()));
            int numberOfLevels = 10;
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
            mNetworkViews.get(NETWORK_WIFI_SIGNAL).get(1)
                    .setText(String.format("%%%d", 100 * level / numberOfLevels));
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
    try {
        // ----- Network Traffic-----
        // int uid = android.os.Process.myUid();
        mNetworkViews.get(NETWORK_RCV_BYTES).get(1).setText(String.format("%d", consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(1).setText(String.format("%d", consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(1).setText(String.format("%d", consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(1).setText(String.format("%d", consoleState.netTxPacks));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes()));
        mNetworkViews.get(NETWORK_RCV_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));
        mNetworkViews.get(NETWORK_SND_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes()));
        mNetworkViews.get(NETWORK_SND_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes() - consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes() - consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netTxPacks));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // ----- Memory -----
    try {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        long heapUsing = Debug.getNativeHeapSize();

        Date now = new Date();
        long deltaMsec = now.getTime() - consoleState.lastFreeze.getTime();

        List<TextView> timeViews = mMemoryViews.get(MEMORY_TIME);
        timeViews.get(1).setText(TIMEFORMAT.format(consoleState.lastFreeze));
        timeViews.get(2).setText(TIMEFORMAT.format(now));
        timeViews.get(3).setText(
                DateUtils.getRelativeTimeSpanString(consoleState.lastFreeze.getTime(), now.getTime(), 0));
        // timeViews.get(3).setText( String.valueOf(deltaMsec));

        List<TextView> usingViews = mMemoryViews.get(MEMORY_USING);
        usingViews.get(1).setText(String.format("%d", consoleState.usingMemory));
        usingViews.get(2).setText(String.format("%d", heapUsing));
        usingViews.get(3).setText(String.format("%d", heapUsing - consoleState.usingMemory));

        List<TextView> freeViews = mMemoryViews.get(MEMORY_FREE);
        freeViews.get(1).setText(String.format("%d", consoleState.freeMemory));
        freeViews.get(2).setText(String.format("%d", mi.availMem));
        freeViews.get(3).setText(String.format("%d", mi.availMem - consoleState.freeMemory));

        List<TextView> totalViews = mMemoryViews.get(MEMORY_TOTAL);
        if (Build.VERSION.SDK_INT >= 16) {
            totalViews.get(1).setText(String.format("%d", consoleState.totalMemory));
            totalViews.get(2).setText(String.format("%d", mi.totalMem));
            totalViews.get(3).setText(String.format("%d", mi.totalMem - consoleState.totalMemory));
        } else {
            totalViews.get(0).setVisibility(View.GONE);
            totalViews.get(1).setVisibility(View.GONE);
            totalViews.get(2).setVisibility(View.GONE);
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

private void snapConsole() {
    try {/*from  w  w  w. j  a va2 s.  c  o  m*/
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        consoleState.lastFreeze = new Date();
        consoleState.usingMemory = Debug.getNativeHeapSize();
        consoleState.freeMemory = mi.availMem;
        if (Build.VERSION.SDK_INT >= 16) {
            consoleState.totalMemory = mi.totalMem;
        }

        consoleState.netRxBytes = TrafficStats.getTotalRxBytes();
        consoleState.netRxPacks = TrafficStats.getTotalRxPackets();
        consoleState.netTxBytes = TrafficStats.getTotalTxBytes();
        consoleState.netTxPacks = TrafficStats.getTotalRxPackets();

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        consoleState.processCnt = actMgr.getRunningAppProcesses().size();
        consoleState.batteryLevel = calculateBatteryLevel(getActivity());
    } catch (Exception ex) {
    }
}