Example usage for android.net TrafficStats getUidTxBytes

List of usage examples for android.net TrafficStats getUidTxBytes

Introduction

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

Prototype

public static long getUidTxBytes(int uid) 

Source Link

Document

Return number of bytes transmitted by the given UID since device boot.

Usage

From source file:Main.java

public static long getUidTBytes(int uid) {
    long tBytes = TrafficStats.getUidTxBytes(uid);
    return tBytes;
}

From source file:my.home.lehome.fragment.HomeStateFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    }//from  ww w. j a v  a 2  s. c  o m
    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();
}

From source file:fr.inria.ucn.collectors.AppDataUsageCollector.java

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private JSONObject getProcInfo(Context c, int uid) throws JSONException {
    // uid + related package list
    JSONObject pinfo = new JSONObject();
    pinfo.put("uid", uid);
    pinfo.put("packages", Helpers.getPackagesForUid(c, uid));

    // simple TCP stats
    JSONObject tcp = new JSONObject();
    tcp.put("send", getSysLongValue(PROC_UID_STAT + "/" + uid + "/tcp_snd"));
    tcp.put("recv", getSysLongValue(PROC_UID_STAT + "/" + uid + "/tcp_rcv"));
    pinfo.put("proc_uid_stat_tcp", tcp);

    // complete traffic stats (may not be available)
    JSONObject tstat = new JSONObject();
    tstat.put("uid_rx_bytes", TrafficStats.getUidRxBytes(uid));
    tstat.put("uid_tx_bytes", TrafficStats.getUidTxBytes(uid));

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
        tstat.put("uid_rx_pkts", TrafficStats.getUidRxPackets(uid));
        tstat.put("uid_tx_pkts", TrafficStats.getUidTxPackets(uid));
        tstat.put("uid_tcp_rx_pkts", TrafficStats.getUidTcpRxSegments(uid));
        tstat.put("uid_tcp_tx_pkts", TrafficStats.getUidTcpTxSegments(uid));
        tstat.put("uid_udp_rx_pkts", TrafficStats.getUidUdpRxPackets(uid));
        tstat.put("uid_udp_tx_pkts", TrafficStats.getUidUdpTxPackets(uid));
        tstat.put("uid_udp_rx_bytes", TrafficStats.getUidUdpRxBytes(uid));
        tstat.put("uid_udp_tx_bytes", TrafficStats.getUidUdpTxBytes(uid));
        tstat.put("uid_tcp_rx_bytes", TrafficStats.getUidTcpRxBytes(uid));
        tstat.put("uid_tcp_tx_bytes", TrafficStats.getUidTcpTxBytes(uid));
    }/*from   w w w  .  j  a  va 2  s.  c o  m*/

    pinfo.put("android_traffic_stats", tstat);
    return pinfo;
}

From source file:com.android.profilerapp.network.NetworkFragment.java

private Thread getStatisticThread() {
    return new Thread(new Runnable() {

        private Statistics statistics;
        private long[] myStartBytes;
        private long[] myBytes;

        private void initialize() {
            statistics = new Statistics();
            myStartBytes = getTrafficBytes(Integer.toString(myUid));
        }/* w w w.j a  va2 s.  c  o  m*/

        @Override
        public void run() {
            initialize();
            while (!Thread.currentThread().isInterrupted()) {
                myBytes = getTrafficBytes(Integer.toString(myUid));
                statistics.sendBytesFromFile = myBytes[0] - myStartBytes[0];
                statistics.receiveBytesFromFile = myBytes[1] - myStartBytes[1];

                // Gets the bytes from API too, because API read is later than file read, API results may be a little larger.
                myBytes[0] = TrafficStats.getUidTxBytes(myUid) - myStartBytes[0];
                myBytes[1] = TrafficStats.getUidRxBytes(myUid) - myStartBytes[1];
                if (statistics.sendBytesFromFile > myBytes[0] || statistics.receiveBytesFromFile > myBytes[1]) {
                    Log.d(TAG, String.format(
                            "Bytes reported not in sync. TrafficStats: %1$d, %2$d, getTrafficBytes: %3$d, %4$d",
                            myBytes[0], myBytes[1], statistics.sendBytesFromFile,
                            statistics.receiveBytesFromFile));
                }

                NetworkInfo networkInfo = myConnectivityManager.getActiveNetworkInfo();
                statistics.networkName = networkInfo != null
                        && networkInfo.getSubtype() != TelephonyManager.NETWORK_TYPE_UNKNOWN
                                ? networkInfo.getSubtypeName()
                                : networkInfo.getTypeName();
                statistics.radioStatus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                        ? myConnectivityManager.isDefaultNetworkActive() ? "Radio high power"
                                : "Radio not high power"
                        : "Radio status unknown";
                statistics.openConnectionCount = getConnectionCount(Integer.toString(myUid));
                postStatistics(statistics);
                try {
                    Thread.currentThread().sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

From source file:eu.liveGov.gordexola.urbanplanning.activities.MainActivity.java

@SuppressLint("NewApi")
@Override/*from   w  w  w.  j  a  v a  2 s . c  om*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        Process process = Runtime.getRuntime().exec("logcat -c");
    } catch (IOException e) {
        Log.e("MainActivity", "I was unable to clear LogCat");
    }
    _savedInstanceState = savedInstanceState;
    configureLogbackDirectly();

    tracker = EasyTracker.getInstance(this);
    setContentView(R.layout.activity_main);
    initialiseTabHost();
    initialisePager();
    ctx = this;

    //------ Location Service Start --------------------
    Functions.startLocationService(ctx);

    //------------ Measure kb downloaded ----------------
    uid = this.getApplicationInfo().uid;
    mStartRX = TrafficStats.getUidRxBytes(uid);
    mStartTX = TrafficStats.getUidTxBytes(uid);

    //------------ Menu hard or soft key ------------------
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        boolean hasMenuKey = ViewConfiguration.get(ctx).hasPermanentMenuKey();

        ActionBar actionBar = getActionBar();
        if (!hasMenuKey) {
            actionBar.show();
        } else {
            actionBar.hide();

        }
    }

    //------------------ Temperature -----------------------------------
    mReceiver_Temperature = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
            if (temperature > 450) {
                String mes = getString(R.string.tempwarn);
                int fullstopIndex = mes.indexOf(".");

                mes = mes.replace("XXXXX", Float.toString((((float) temperature) / 10)) + "\u2103");
                String mesA = mes.substring(0, fullstopIndex);
                Toast.makeText(ctx, mesA, Toast.LENGTH_LONG).show();
                String mesB = mes.substring(fullstopIndex + 2);
                Toast.makeText(ctx, mesB, Toast.LENGTH_LONG).show();
            }
        }
    };

    //--------------- Remove Transparency and Enable -------------------------------
    intentFilter = new IntentFilter("android.intent.action.MAIN"); // DataCh
    mReceiverARFinished = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String ARFINISHED = intent.getStringExtra("ARFINISHED");
            Integer ARDATAPLUSVal = intent.getIntExtra("DataPlus", 0);

            if (ARFINISHED != null) {
                Log.e("AR Finished", "ok 2");

                if (pbarGeneral != null)
                    pbarGeneral.setProgress(90);

                Message msg = new Message();
                msg.arg1 = 2;
                handlerDialog.sendMessage(msg);

            } else if (ARDATAPLUSVal != 0) {
                if (pbarGeneral != null) {

                    if (ARDATAPLUSVal > 90)
                        ARDATAPLUSVal = 90;

                    pbarGeneral.setProgress(ARDATAPLUSVal);
                } else {
                    if (ARDATAPLUSVal < 15) {
                        Message msg = new Message();
                        msg.arg1 = 1;
                        handlerDialog.sendMessage(msg);
                    }
                }
            }
        }
    };
    registerReceiver(mReceiverARFinished, intentFilter);

    //----- Handler for Redrawing Markers from update thread ------------
    handlerDialog = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.arg1 == 1) {
                if (progressReceiving == null) {
                    progressReceiving = ProgressDialog.show(ctx, "", "", true);
                    progressReceiving.setContentView(R.layout.dialog_transparent_progress);
                    pbarGeneral = (ProgressBar) progressReceiving.findViewById(R.id.allprogress);
                }
            } else {
                if (progressReceiving != null && progressReceiving.isShowing())
                    progressReceiving.dismiss();

                progressReceiving = null;
            }
            super.handleMessage(msg);
        }
    };

    if (Functions.checkInternetConnection(this) && Functions.hasNetLocationProviderEnabled(this)
            && Functions.hasGPSLocationProviderEnabled(this)) {
        // Show progress transparency
        Message msg = new Message();
        msg.arg1 = 1;
        handlerDialog.sendMessage(msg);
    }
}

From source file:de.qspool.clementineremote.backend.ClementinePlayerConnection.java

/**
 * Try to connect to Clementine//from ww w  .j  ava  2s .  c  om
 *
 * @param message The Request Object. Stores the ip to connect to.
 */
@Override
public boolean createConnection(ClementineMessage message) {
    // 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
        mLastSong = null;
        mLastState = App.mClementine.getState();

        // Setup the MediaButtonReceiver and the RemoteControlClient
        registerRemoteControlClient();

        // Register MediaButtonReceiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
        App.mApp.registerReceiver(mMediaButtonBroadcastReceiver, filter);

        updateNotification();

        // The device shall be awake
        mWakeLock.acquire();

        // 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.mApp.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();
                    if (!m.isErrorMessage() || m.getErrorMessage() != ErrorMessage.TIMEOUT) {
                        Message msg = Message.obtain();
                        msg.obj = m;
                        msg.arg1 = PROCESS_PROTOC;
                        mHandler.sendMessage(msg);
                    }
                }
                Log.d(TAG, "reading thread exit");
            }
        });
        mIncomingThread.start();

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

    return connected;
}

From source file:eu.liveGov.gordexola.urbanplanning.activities.MainActivity.java

public boolean onOptionsItemSelected(MenuItem item) {
    Intent i;//from  ww w .  j  a  v  a 2s.c o  m
    switch (item.getItemId()) {
    case R.id.User_information:
        i = new Intent(this, UserInformationActivity.class);
        startActivity(i);
        return true;
    case R.id.about_id:
        i = new Intent(this, AboutActivity.class);
        startActivity(i);
        return true;
    case R.id.myDebugItem_id: //myloc_id:
        i = new Intent(this, DebugInfoActivity.class);
        i.putExtra("kbgot", TrafficStats.getUidRxBytes(uid) - mStartRX);
        i.putExtra("kbsend", TrafficStats.getUidTxBytes(uid) - mStartTX);
        startActivity(i);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:eu.operando.operandoapp.OperandoProxyStatus.java

private String GetDataForApp(int uid) {
    String total;/*from   w w  w  . j av a  2  s. c  o m*/
    try {
        //round to 2 decimal places
        total = Math.round((TrafficStats.getUidTxBytes(uid) / (1024.0 * 1024.0)) * 100.0) / 100.0 + " MB / "
                + Math.round((TrafficStats.getUidRxBytes(uid) / (1024.0 * 1024.0)) * 100.0) / 100.0 + " MB";
    } catch (Exception e) {
        total = "0 MB / 0 MB";
    }
    return total;
}