I am working on a wifi data usage research and want to develop a program like,When user click on a button the device is already connected to wifi will start computing data usage and on same button click it will stop computing data usage and give me total data usage between start and stop event.I have searched many threads related to this but didnt find what i am looking for,Can any one help me for the same,THis is what i have tried a little. code
public class MainActivity extends AppCompatActivity {
NetworkInfo wifiCheck;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
getDataWifiDataUsageInfo();
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
wifiCheck = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiCheck.isConnected()) {
// Do whatever here
Toast.makeText(MainActivity.this,"WiFi is Connected",Toast.LENGTH_LONG);
} else {
Toast.makeText(MainActivity.this,"WiFi is not Connected",Toast.LENGTH_LONG);
}
}
public void checkWiFi(View view) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
//get data usage info
void getDataWifiDataUsageInfo(){
Log.e("bytes recvd", "" + android.net.TrafficStats.getMobileRxBytes());
Log.e("Total", "Bytes received" + android.net.TrafficStats.getTotalRxBytes());
}
}
I hope someone will definitely help me.Looking for a help.
If you already know that the user is connected to WiFi (as you stated) when clicking the button, all networking (sending and receiving of data) will go through the WiFi connection. Thus, when the user clicks on the button to start:
long startBytes = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
and when the stop button is clicked:
long stopBytes = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
Finally, to work out the bytes transferred between start and stop:
long bytesTransferred = stopBytes - startBytes;
For more information check out the TrafficStats methods used here and here.