Example usage for android.net TrafficStats getTotalTxBytes

List of usage examples for android.net TrafficStats getTotalTxBytes

Introduction

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

Prototype

public static long getTotalTxBytes() 

Source Link

Document

Return number of bytes transmitted since device boot.

Usage

From source file:Main.java

public static long getNetTxTotalBytes() {
    long total = TrafficStats.getTotalTxBytes();
    return total;
}

From source file:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java

public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) {
    Log.v(TAG, "upload " + uploadConfig);
    // Make sure we have a file to upload
    if (!uploadConfig.file.exists())
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);

    FTPClient ftp = new FTPClient();
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }//from  w  w  w. jav a 2  s.c o m
    InputStream is = null;
    try {
        // Set buffer size of FTP client
        ftp.setBufferSize(1048576);
        // Open a connection to the FTP server
        ftp.connect(uploadConfig.server, uploadConfig.port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Login to the FTP server
        if (!ftp.login(uploadConfig.user, uploadConfig.password)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE);
        }
        // Try to change directories
        if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) {
            Log.v(TAG, "Upload: could not change path to " + uploadConfig.path);
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
        }

        // set the file type to be read as a binary file
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        // Upload the file
        is = new FileInputStream(uploadConfig.file);
        long before = System.currentTimeMillis();
        long txBytesBefore = TrafficStats.getTotalTxBytes();
        if (!ftp.storeFile(uploadConfig.file.getName(), is)) {
            ftp.disconnect();
            Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: "
                    + ftp.getReplyCode() + ", error string: " + ftp.getReplyString());
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }

        // Calculate stats
        long after = System.currentTimeMillis();
        long txBytesAfter = TrafficStats.getTotalTxBytes();
        ftp.logout();
        ftp.disconnect();
        Log.v(TAG, "Upload complete");
        return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before,
                SpeedTestStatus.SUCCESS);
    } catch (SocketException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } catch (IOException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } finally {
        IoUtil.closeSilently(is);
    }
}

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

private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException {
    mCancelable = false;/*from   w  ww.  j  ava  2s.  co  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");
        }//from w  w  w . ja va2 s .  c om
    }
}

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

public long get_txCurrentBytes() {
    final long totalTxBytes = TrafficStats.getTotalTxBytes();
    if (totalTxBytes != TrafficStats.UNSUPPORTED) {
        mTxCurrentBytes = totalTxBytes - mTxStartBytes;
    } else {/*w w w  .ja  v  a 2 s .c o m*/
        mTxCurrentBytes = 0;
    }
    return mTxCurrentBytes;
}

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

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

    if (mSystemViews.isEmpty())
        return;//from   ww  w .jav a  2s .co  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 {/* w  ww .j  ava  2  s  . c  om*/
        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) {
    }
}