Determine transfer rate of upload
I am working on an app which uploads a large amount of data. I want to determine the transfer rate of the upload, to show in a notification.
- One post suggests using the
WifiInfo
which will not work for mobile data. - Another post suggests getting the network type to estimate the speed.
I'm not satisfied with the answers in these posts, so I am asking again.
I've seen apps which display the upload transfer rate, as well as some custom ROMs like Resurrection Remix.
How can I determine the transfer rate of these uploads?
java android okhttp android-networking android-internet
|
show 14 more comments
I am working on an app which uploads a large amount of data. I want to determine the transfer rate of the upload, to show in a notification.
- One post suggests using the
WifiInfo
which will not work for mobile data. - Another post suggests getting the network type to estimate the speed.
I'm not satisfied with the answers in these posts, so I am asking again.
I've seen apps which display the upload transfer rate, as well as some custom ROMs like Resurrection Remix.
How can I determine the transfer rate of these uploads?
java android okhttp android-networking android-internet
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 9:33
Have you tried CellInfoGsm ?
– Sz-Nika Janos
Nov 28 '18 at 9:36
Maybe this library helps: github.com/facebook/network-connection-class
– leonardkraemer
Nov 28 '18 at 10:09
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 10:33
2
I am willing to give 200+ if I get an answer. Through a dummy question or something - better not tell the mods about that plan
– Tim Castelijns
Nov 28 '18 at 10:53
|
show 14 more comments
I am working on an app which uploads a large amount of data. I want to determine the transfer rate of the upload, to show in a notification.
- One post suggests using the
WifiInfo
which will not work for mobile data. - Another post suggests getting the network type to estimate the speed.
I'm not satisfied with the answers in these posts, so I am asking again.
I've seen apps which display the upload transfer rate, as well as some custom ROMs like Resurrection Remix.
How can I determine the transfer rate of these uploads?
java android okhttp android-networking android-internet
I am working on an app which uploads a large amount of data. I want to determine the transfer rate of the upload, to show in a notification.
- One post suggests using the
WifiInfo
which will not work for mobile data. - Another post suggests getting the network type to estimate the speed.
I'm not satisfied with the answers in these posts, so I am asking again.
I've seen apps which display the upload transfer rate, as well as some custom ROMs like Resurrection Remix.
How can I determine the transfer rate of these uploads?
java android okhttp android-networking android-internet
java android okhttp android-networking android-internet
edited Dec 2 '18 at 6:55
aminography
6,29521534
6,29521534
asked Nov 20 '18 at 12:38
user10655681
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 9:33
Have you tried CellInfoGsm ?
– Sz-Nika Janos
Nov 28 '18 at 9:36
Maybe this library helps: github.com/facebook/network-connection-class
– leonardkraemer
Nov 28 '18 at 10:09
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 10:33
2
I am willing to give 200+ if I get an answer. Through a dummy question or something - better not tell the mods about that plan
– Tim Castelijns
Nov 28 '18 at 10:53
|
show 14 more comments
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 9:33
Have you tried CellInfoGsm ?
– Sz-Nika Janos
Nov 28 '18 at 9:36
Maybe this library helps: github.com/facebook/network-connection-class
– leonardkraemer
Nov 28 '18 at 10:09
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 10:33
2
I am willing to give 200+ if I get an answer. Through a dummy question or something - better not tell the mods about that plan
– Tim Castelijns
Nov 28 '18 at 10:53
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 9:33
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 9:33
Have you tried CellInfoGsm ?
– Sz-Nika Janos
Nov 28 '18 at 9:36
Have you tried CellInfoGsm ?
– Sz-Nika Janos
Nov 28 '18 at 9:36
Maybe this library helps: github.com/facebook/network-connection-class
– leonardkraemer
Nov 28 '18 at 10:09
Maybe this library helps: github.com/facebook/network-connection-class
– leonardkraemer
Nov 28 '18 at 10:09
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 10:33
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 10:33
2
2
I am willing to give 200+ if I get an answer. Through a dummy question or something - better not tell the mods about that plan
– Tim Castelijns
Nov 28 '18 at 10:53
I am willing to give 200+ if I get an answer. Through a dummy question or something - better not tell the mods about that plan
– Tim Castelijns
Nov 28 '18 at 10:53
|
show 14 more comments
3 Answers
3
active
oldest
votes
It is feasible to obtain the transferred traffic amount using android.net.TrafficStats
. Here is an implementation of this idea which measures the up-stream and down-stream transfer rate. You can measure the rate of mobile network by passing TrafficSpeedMeasurer.TrafficType.MOBILE
to the TrafficSpeedMeasurer
constructor, otherwise using TrafficSpeedMeasurer.TrafficType.ALL
will result in measuring general traffic (WiFi/Mobile). Also by setting SHOW_SPEED_IN_BITS = true
in MainActivity
you can change the unit of speed measuring to bit
s per second.
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final boolean SHOW_SPEED_IN_BITS = false;
private TrafficSpeedMeasurer mTrafficSpeedMeasurer;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.connection_class);
mTrafficSpeedMeasurer = new TrafficSpeedMeasurer(TrafficSpeedMeasurer.TrafficType.ALL);
mTrafficSpeedMeasurer.startMeasuring();
}
@Override
protected void onDestroy() {
super.onDestroy();
mTrafficSpeedMeasurer.stopMeasuring();
}
@Override
protected void onPause() {
super.onPause();
mTrafficSpeedMeasurer.removeListener(mStreamSpeedListener);
}
@Override
protected void onResume() {
super.onResume();
mTrafficSpeedMeasurer.registerListener(mStreamSpeedListener);
}
private ITrafficSpeedListener mStreamSpeedListener = new ITrafficSpeedListener() {
@Override
public void onTrafficSpeedMeasured(final double upStream, final double downStream) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String upStreamSpeed = Utils.parseSpeed(upStream, SHOW_SPEED_IN_BITS);
String downStreamSpeed = Utils.parseSpeed(downStream, SHOW_SPEED_IN_BITS);
mTextView.setText("Up Stream Speed: " + upStreamSpeed + "n" + "Down Stream Speed: " + downStreamSpeed);
}
});
}
};
}
TrafficSpeedMeasurer.java
import android.net.TrafficStats;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
public class TrafficSpeedMeasurer {
private ITrafficSpeedListener mTrafficSpeedListener;
private SamplingHandler mHandler;
private TrafficType mTrafficType;
private long mLastTimeReading;
private long mPreviousUpStream = -1;
private long mPreviousDownStream = -1;
public TrafficSpeedMeasurer(TrafficType trafficType) {
mTrafficType = trafficType;
HandlerThread thread = new HandlerThread("ParseThread");
thread.start();
mHandler = new SamplingHandler(thread.getLooper());
}
public void registerListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void removeListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void startMeasuring() {
mHandler.startSamplingThread();
mLastTimeReading = SystemClock.elapsedRealtime();
}
public void stopMeasuring() {
mHandler.stopSamplingThread();
finalReadTrafficStats();
}
private void readTrafficStats() {
long newBytesUpStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileTxBytes() : TrafficStats.getTotalTxBytes()) * 1024;
long newBytesDownStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileRxBytes() : TrafficStats.getTotalRxBytes()) * 1024;
long byteDiffUpStream = newBytesUpStream - mPreviousUpStream;
long byteDiffDownStream = newBytesDownStream - mPreviousDownStream;
synchronized (this) {
long currentTime = SystemClock.elapsedRealtime();
double bandwidthUpStream = 0;
double bandwidthDownStream = 0;
if (mPreviousUpStream >= 0) {
bandwidthUpStream = (byteDiffUpStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mPreviousDownStream >= 0) {
bandwidthDownStream = (byteDiffDownStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mTrafficSpeedListener != null) {
mTrafficSpeedListener.onTrafficSpeedMeasured(bandwidthUpStream, bandwidthDownStream);
}
mLastTimeReading = currentTime;
}
mPreviousDownStream = newBytesDownStream;
mPreviousUpStream = newBytesUpStream;
}
private void finalReadTrafficStats() {
readTrafficStats();
mPreviousUpStream = -1;
mPreviousDownStream = -1;
}
private class SamplingHandler extends Handler {
private static final long SAMPLE_TIME = 1000;
private static final int MSG_START = 1;
private SamplingHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_START:
readTrafficStats();
sendEmptyMessageDelayed(MSG_START, SAMPLE_TIME);
break;
default:
throw new IllegalArgumentException("Unknown what=" + msg.what);
}
}
void startSamplingThread() {
sendEmptyMessage(SamplingHandler.MSG_START);
}
void stopSamplingThread() {
removeMessages(SamplingHandler.MSG_START);
}
}
public enum TrafficType {
MOBILE,
ALL
}
}
ITrafficSpeedListener.java
public interface ITrafficSpeedListener {
void onTrafficSpeedMeasured(double upStream, double downStream);
}
Utils.java
import java.util.Locale;
public class Utils {
private static final long B = 1;
private static final long KB = B * 1024;
private static final long MB = KB * 1024;
private static final long GB = MB * 1024;
public static String parseSpeed(double bytes, boolean inBits) {
double value = inBits ? bytes * 8 : bytes;
if (value < KB) {
return String.format(Locale.getDefault(), "%.1f " + (inBits ? "b" : "B") + "/s", value);
} else if (value < MB) {
return String.format(Locale.getDefault(), "%.1f K" + (inBits ? "b" : "B") + "/s", value / KB);
} else if (value < GB) {
return String.format(Locale.getDefault(), "%.1f M" + (inBits ? "b" : "B") + "/s", value / MB);
} else {
return String.format(Locale.getDefault(), "%.2f G" + (inBits ? "b" : "B") + "/s", value / GB);
}
}
}
.
Visual Result
This gives you the rate of all traffic over the network. This doesn't help you determine the upload rate of a particular HTTP request.
– Tim Malseed
Dec 2 '18 at 4:37
1
@TimMalseed: It is possible to measure traffic of a specific app usingTrafficStats.getUidTxBytes (int uid)
andTrafficStats.getUidRxBytes (int uid)
. You can see that the question mentioned a custom ROM namedResurrection Remix
which shows all traffic rate in status bar and he wants it according to: "as well as some custom ROMs". However, thank you for your down vote :)
– aminography
Dec 2 '18 at 5:09
Sure, but it's not possible to get the transfer rate of a particular HTTP request. Don't take it personally, it's just unfortunate that OP has not been very clear with the question and this is more of a compromise than a correct solution. I appreciate you detailing the possibilities ofTrafficStats
, and it is an interesting alternative. This answer is useful though, and doesn't deserve to be downvoted, so I apologise for that.
– Tim Malseed
Dec 2 '18 at 5:14
It's good to be aware answers like this one, I'm just wary of accepting and upvoting them as the 'correct' answer because it misleads less experienced developers. If the intention is to display the transfer rate of a particular upload to the user, and instead they display the transfer rate of all traffic, that's not technically correct, and could be wildly inaccurate depending on what else is going on on the device. What wasn't clear is OP was interested in simplicity over accuracy, which is understandable.
– Tim Malseed
Dec 2 '18 at 5:18
I agree with you, the intention of this question is a bit ambiguous. However if you bypass its title, I think above approach would be acceptable.
– aminography
Dec 2 '18 at 5:27
|
show 2 more comments
What you're trying to determine is the transfer rate of the bytes being uploaded over your HTTP Client. Obviously, this depends on the HTTP client you're using.
There's no out-of-the-box solution which applies to all HTTP clients used on Android. The Android SDK does not provide any methods for you to determine the transfer rate of a particular upload.
Fortunately, you're using OKHttp and there is a relatively straight-forward way to do this. You're going to have to implement a custom RequestBody
, and observe the bytes being written to the buffer when the request is in flight.
There's a 'recipe' for doing this on the OkHttp Github:
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
You could also refer to this StackOverflow question dealing with the exact same topic:
Tracking progress of multipart file upload using OKHTTP
Another here:
OKHTTP 3 Tracking Multipart upload progress
Isn't this the same answer as mine?
– Murat Karagöz
Nov 29 '18 at 9:29
I don't think so, but we do both reference the same duplicate question. This question really should be closed, but OP has decided to use their bounty in order to prevent the question from being closed,
– Tim Malseed
Nov 29 '18 at 9:35
1
@PembaTamang you were asking for the upload rate of a particular HTTP request, but you've accepted an an answer which gives you the upload rate of ALL requests, even those uploads not started by your app.
– Tim Malseed
Dec 2 '18 at 4:39
add a comment |
I am talking in the context of your app since this makes it easier to capture the real time speed of your uploaded data. You don't need any extra libraries or sdk api's.
You are presumably uploading the data in chunks to the server. So
a) You know the data size of each packet
b) You know the start time before sending the packet / before sending multiple packets
c) You know the end time of xy packets by the server response e.g. status 200
With that you have all parameters to calculate the upload speed
double uploadSpeed = packet.size / (endTime - startTime)
// time * 1000 to have it in seconds
EDIT:
Since you are using MultiPart
from OkHttp
you can monitor the amount of bytes uploaded. Tracking progress of multipart file upload using OKHTTP. You would replace packet.size
with the current uploaded amount and the endTime
would be an interval of xy seconds.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393180%2fdetermine-transfer-rate-of-upload%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
It is feasible to obtain the transferred traffic amount using android.net.TrafficStats
. Here is an implementation of this idea which measures the up-stream and down-stream transfer rate. You can measure the rate of mobile network by passing TrafficSpeedMeasurer.TrafficType.MOBILE
to the TrafficSpeedMeasurer
constructor, otherwise using TrafficSpeedMeasurer.TrafficType.ALL
will result in measuring general traffic (WiFi/Mobile). Also by setting SHOW_SPEED_IN_BITS = true
in MainActivity
you can change the unit of speed measuring to bit
s per second.
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final boolean SHOW_SPEED_IN_BITS = false;
private TrafficSpeedMeasurer mTrafficSpeedMeasurer;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.connection_class);
mTrafficSpeedMeasurer = new TrafficSpeedMeasurer(TrafficSpeedMeasurer.TrafficType.ALL);
mTrafficSpeedMeasurer.startMeasuring();
}
@Override
protected void onDestroy() {
super.onDestroy();
mTrafficSpeedMeasurer.stopMeasuring();
}
@Override
protected void onPause() {
super.onPause();
mTrafficSpeedMeasurer.removeListener(mStreamSpeedListener);
}
@Override
protected void onResume() {
super.onResume();
mTrafficSpeedMeasurer.registerListener(mStreamSpeedListener);
}
private ITrafficSpeedListener mStreamSpeedListener = new ITrafficSpeedListener() {
@Override
public void onTrafficSpeedMeasured(final double upStream, final double downStream) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String upStreamSpeed = Utils.parseSpeed(upStream, SHOW_SPEED_IN_BITS);
String downStreamSpeed = Utils.parseSpeed(downStream, SHOW_SPEED_IN_BITS);
mTextView.setText("Up Stream Speed: " + upStreamSpeed + "n" + "Down Stream Speed: " + downStreamSpeed);
}
});
}
};
}
TrafficSpeedMeasurer.java
import android.net.TrafficStats;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
public class TrafficSpeedMeasurer {
private ITrafficSpeedListener mTrafficSpeedListener;
private SamplingHandler mHandler;
private TrafficType mTrafficType;
private long mLastTimeReading;
private long mPreviousUpStream = -1;
private long mPreviousDownStream = -1;
public TrafficSpeedMeasurer(TrafficType trafficType) {
mTrafficType = trafficType;
HandlerThread thread = new HandlerThread("ParseThread");
thread.start();
mHandler = new SamplingHandler(thread.getLooper());
}
public void registerListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void removeListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void startMeasuring() {
mHandler.startSamplingThread();
mLastTimeReading = SystemClock.elapsedRealtime();
}
public void stopMeasuring() {
mHandler.stopSamplingThread();
finalReadTrafficStats();
}
private void readTrafficStats() {
long newBytesUpStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileTxBytes() : TrafficStats.getTotalTxBytes()) * 1024;
long newBytesDownStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileRxBytes() : TrafficStats.getTotalRxBytes()) * 1024;
long byteDiffUpStream = newBytesUpStream - mPreviousUpStream;
long byteDiffDownStream = newBytesDownStream - mPreviousDownStream;
synchronized (this) {
long currentTime = SystemClock.elapsedRealtime();
double bandwidthUpStream = 0;
double bandwidthDownStream = 0;
if (mPreviousUpStream >= 0) {
bandwidthUpStream = (byteDiffUpStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mPreviousDownStream >= 0) {
bandwidthDownStream = (byteDiffDownStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mTrafficSpeedListener != null) {
mTrafficSpeedListener.onTrafficSpeedMeasured(bandwidthUpStream, bandwidthDownStream);
}
mLastTimeReading = currentTime;
}
mPreviousDownStream = newBytesDownStream;
mPreviousUpStream = newBytesUpStream;
}
private void finalReadTrafficStats() {
readTrafficStats();
mPreviousUpStream = -1;
mPreviousDownStream = -1;
}
private class SamplingHandler extends Handler {
private static final long SAMPLE_TIME = 1000;
private static final int MSG_START = 1;
private SamplingHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_START:
readTrafficStats();
sendEmptyMessageDelayed(MSG_START, SAMPLE_TIME);
break;
default:
throw new IllegalArgumentException("Unknown what=" + msg.what);
}
}
void startSamplingThread() {
sendEmptyMessage(SamplingHandler.MSG_START);
}
void stopSamplingThread() {
removeMessages(SamplingHandler.MSG_START);
}
}
public enum TrafficType {
MOBILE,
ALL
}
}
ITrafficSpeedListener.java
public interface ITrafficSpeedListener {
void onTrafficSpeedMeasured(double upStream, double downStream);
}
Utils.java
import java.util.Locale;
public class Utils {
private static final long B = 1;
private static final long KB = B * 1024;
private static final long MB = KB * 1024;
private static final long GB = MB * 1024;
public static String parseSpeed(double bytes, boolean inBits) {
double value = inBits ? bytes * 8 : bytes;
if (value < KB) {
return String.format(Locale.getDefault(), "%.1f " + (inBits ? "b" : "B") + "/s", value);
} else if (value < MB) {
return String.format(Locale.getDefault(), "%.1f K" + (inBits ? "b" : "B") + "/s", value / KB);
} else if (value < GB) {
return String.format(Locale.getDefault(), "%.1f M" + (inBits ? "b" : "B") + "/s", value / MB);
} else {
return String.format(Locale.getDefault(), "%.2f G" + (inBits ? "b" : "B") + "/s", value / GB);
}
}
}
.
Visual Result
This gives you the rate of all traffic over the network. This doesn't help you determine the upload rate of a particular HTTP request.
– Tim Malseed
Dec 2 '18 at 4:37
1
@TimMalseed: It is possible to measure traffic of a specific app usingTrafficStats.getUidTxBytes (int uid)
andTrafficStats.getUidRxBytes (int uid)
. You can see that the question mentioned a custom ROM namedResurrection Remix
which shows all traffic rate in status bar and he wants it according to: "as well as some custom ROMs". However, thank you for your down vote :)
– aminography
Dec 2 '18 at 5:09
Sure, but it's not possible to get the transfer rate of a particular HTTP request. Don't take it personally, it's just unfortunate that OP has not been very clear with the question and this is more of a compromise than a correct solution. I appreciate you detailing the possibilities ofTrafficStats
, and it is an interesting alternative. This answer is useful though, and doesn't deserve to be downvoted, so I apologise for that.
– Tim Malseed
Dec 2 '18 at 5:14
It's good to be aware answers like this one, I'm just wary of accepting and upvoting them as the 'correct' answer because it misleads less experienced developers. If the intention is to display the transfer rate of a particular upload to the user, and instead they display the transfer rate of all traffic, that's not technically correct, and could be wildly inaccurate depending on what else is going on on the device. What wasn't clear is OP was interested in simplicity over accuracy, which is understandable.
– Tim Malseed
Dec 2 '18 at 5:18
I agree with you, the intention of this question is a bit ambiguous. However if you bypass its title, I think above approach would be acceptable.
– aminography
Dec 2 '18 at 5:27
|
show 2 more comments
It is feasible to obtain the transferred traffic amount using android.net.TrafficStats
. Here is an implementation of this idea which measures the up-stream and down-stream transfer rate. You can measure the rate of mobile network by passing TrafficSpeedMeasurer.TrafficType.MOBILE
to the TrafficSpeedMeasurer
constructor, otherwise using TrafficSpeedMeasurer.TrafficType.ALL
will result in measuring general traffic (WiFi/Mobile). Also by setting SHOW_SPEED_IN_BITS = true
in MainActivity
you can change the unit of speed measuring to bit
s per second.
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final boolean SHOW_SPEED_IN_BITS = false;
private TrafficSpeedMeasurer mTrafficSpeedMeasurer;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.connection_class);
mTrafficSpeedMeasurer = new TrafficSpeedMeasurer(TrafficSpeedMeasurer.TrafficType.ALL);
mTrafficSpeedMeasurer.startMeasuring();
}
@Override
protected void onDestroy() {
super.onDestroy();
mTrafficSpeedMeasurer.stopMeasuring();
}
@Override
protected void onPause() {
super.onPause();
mTrafficSpeedMeasurer.removeListener(mStreamSpeedListener);
}
@Override
protected void onResume() {
super.onResume();
mTrafficSpeedMeasurer.registerListener(mStreamSpeedListener);
}
private ITrafficSpeedListener mStreamSpeedListener = new ITrafficSpeedListener() {
@Override
public void onTrafficSpeedMeasured(final double upStream, final double downStream) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String upStreamSpeed = Utils.parseSpeed(upStream, SHOW_SPEED_IN_BITS);
String downStreamSpeed = Utils.parseSpeed(downStream, SHOW_SPEED_IN_BITS);
mTextView.setText("Up Stream Speed: " + upStreamSpeed + "n" + "Down Stream Speed: " + downStreamSpeed);
}
});
}
};
}
TrafficSpeedMeasurer.java
import android.net.TrafficStats;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
public class TrafficSpeedMeasurer {
private ITrafficSpeedListener mTrafficSpeedListener;
private SamplingHandler mHandler;
private TrafficType mTrafficType;
private long mLastTimeReading;
private long mPreviousUpStream = -1;
private long mPreviousDownStream = -1;
public TrafficSpeedMeasurer(TrafficType trafficType) {
mTrafficType = trafficType;
HandlerThread thread = new HandlerThread("ParseThread");
thread.start();
mHandler = new SamplingHandler(thread.getLooper());
}
public void registerListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void removeListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void startMeasuring() {
mHandler.startSamplingThread();
mLastTimeReading = SystemClock.elapsedRealtime();
}
public void stopMeasuring() {
mHandler.stopSamplingThread();
finalReadTrafficStats();
}
private void readTrafficStats() {
long newBytesUpStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileTxBytes() : TrafficStats.getTotalTxBytes()) * 1024;
long newBytesDownStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileRxBytes() : TrafficStats.getTotalRxBytes()) * 1024;
long byteDiffUpStream = newBytesUpStream - mPreviousUpStream;
long byteDiffDownStream = newBytesDownStream - mPreviousDownStream;
synchronized (this) {
long currentTime = SystemClock.elapsedRealtime();
double bandwidthUpStream = 0;
double bandwidthDownStream = 0;
if (mPreviousUpStream >= 0) {
bandwidthUpStream = (byteDiffUpStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mPreviousDownStream >= 0) {
bandwidthDownStream = (byteDiffDownStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mTrafficSpeedListener != null) {
mTrafficSpeedListener.onTrafficSpeedMeasured(bandwidthUpStream, bandwidthDownStream);
}
mLastTimeReading = currentTime;
}
mPreviousDownStream = newBytesDownStream;
mPreviousUpStream = newBytesUpStream;
}
private void finalReadTrafficStats() {
readTrafficStats();
mPreviousUpStream = -1;
mPreviousDownStream = -1;
}
private class SamplingHandler extends Handler {
private static final long SAMPLE_TIME = 1000;
private static final int MSG_START = 1;
private SamplingHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_START:
readTrafficStats();
sendEmptyMessageDelayed(MSG_START, SAMPLE_TIME);
break;
default:
throw new IllegalArgumentException("Unknown what=" + msg.what);
}
}
void startSamplingThread() {
sendEmptyMessage(SamplingHandler.MSG_START);
}
void stopSamplingThread() {
removeMessages(SamplingHandler.MSG_START);
}
}
public enum TrafficType {
MOBILE,
ALL
}
}
ITrafficSpeedListener.java
public interface ITrafficSpeedListener {
void onTrafficSpeedMeasured(double upStream, double downStream);
}
Utils.java
import java.util.Locale;
public class Utils {
private static final long B = 1;
private static final long KB = B * 1024;
private static final long MB = KB * 1024;
private static final long GB = MB * 1024;
public static String parseSpeed(double bytes, boolean inBits) {
double value = inBits ? bytes * 8 : bytes;
if (value < KB) {
return String.format(Locale.getDefault(), "%.1f " + (inBits ? "b" : "B") + "/s", value);
} else if (value < MB) {
return String.format(Locale.getDefault(), "%.1f K" + (inBits ? "b" : "B") + "/s", value / KB);
} else if (value < GB) {
return String.format(Locale.getDefault(), "%.1f M" + (inBits ? "b" : "B") + "/s", value / MB);
} else {
return String.format(Locale.getDefault(), "%.2f G" + (inBits ? "b" : "B") + "/s", value / GB);
}
}
}
.
Visual Result
This gives you the rate of all traffic over the network. This doesn't help you determine the upload rate of a particular HTTP request.
– Tim Malseed
Dec 2 '18 at 4:37
1
@TimMalseed: It is possible to measure traffic of a specific app usingTrafficStats.getUidTxBytes (int uid)
andTrafficStats.getUidRxBytes (int uid)
. You can see that the question mentioned a custom ROM namedResurrection Remix
which shows all traffic rate in status bar and he wants it according to: "as well as some custom ROMs". However, thank you for your down vote :)
– aminography
Dec 2 '18 at 5:09
Sure, but it's not possible to get the transfer rate of a particular HTTP request. Don't take it personally, it's just unfortunate that OP has not been very clear with the question and this is more of a compromise than a correct solution. I appreciate you detailing the possibilities ofTrafficStats
, and it is an interesting alternative. This answer is useful though, and doesn't deserve to be downvoted, so I apologise for that.
– Tim Malseed
Dec 2 '18 at 5:14
It's good to be aware answers like this one, I'm just wary of accepting and upvoting them as the 'correct' answer because it misleads less experienced developers. If the intention is to display the transfer rate of a particular upload to the user, and instead they display the transfer rate of all traffic, that's not technically correct, and could be wildly inaccurate depending on what else is going on on the device. What wasn't clear is OP was interested in simplicity over accuracy, which is understandable.
– Tim Malseed
Dec 2 '18 at 5:18
I agree with you, the intention of this question is a bit ambiguous. However if you bypass its title, I think above approach would be acceptable.
– aminography
Dec 2 '18 at 5:27
|
show 2 more comments
It is feasible to obtain the transferred traffic amount using android.net.TrafficStats
. Here is an implementation of this idea which measures the up-stream and down-stream transfer rate. You can measure the rate of mobile network by passing TrafficSpeedMeasurer.TrafficType.MOBILE
to the TrafficSpeedMeasurer
constructor, otherwise using TrafficSpeedMeasurer.TrafficType.ALL
will result in measuring general traffic (WiFi/Mobile). Also by setting SHOW_SPEED_IN_BITS = true
in MainActivity
you can change the unit of speed measuring to bit
s per second.
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final boolean SHOW_SPEED_IN_BITS = false;
private TrafficSpeedMeasurer mTrafficSpeedMeasurer;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.connection_class);
mTrafficSpeedMeasurer = new TrafficSpeedMeasurer(TrafficSpeedMeasurer.TrafficType.ALL);
mTrafficSpeedMeasurer.startMeasuring();
}
@Override
protected void onDestroy() {
super.onDestroy();
mTrafficSpeedMeasurer.stopMeasuring();
}
@Override
protected void onPause() {
super.onPause();
mTrafficSpeedMeasurer.removeListener(mStreamSpeedListener);
}
@Override
protected void onResume() {
super.onResume();
mTrafficSpeedMeasurer.registerListener(mStreamSpeedListener);
}
private ITrafficSpeedListener mStreamSpeedListener = new ITrafficSpeedListener() {
@Override
public void onTrafficSpeedMeasured(final double upStream, final double downStream) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String upStreamSpeed = Utils.parseSpeed(upStream, SHOW_SPEED_IN_BITS);
String downStreamSpeed = Utils.parseSpeed(downStream, SHOW_SPEED_IN_BITS);
mTextView.setText("Up Stream Speed: " + upStreamSpeed + "n" + "Down Stream Speed: " + downStreamSpeed);
}
});
}
};
}
TrafficSpeedMeasurer.java
import android.net.TrafficStats;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
public class TrafficSpeedMeasurer {
private ITrafficSpeedListener mTrafficSpeedListener;
private SamplingHandler mHandler;
private TrafficType mTrafficType;
private long mLastTimeReading;
private long mPreviousUpStream = -1;
private long mPreviousDownStream = -1;
public TrafficSpeedMeasurer(TrafficType trafficType) {
mTrafficType = trafficType;
HandlerThread thread = new HandlerThread("ParseThread");
thread.start();
mHandler = new SamplingHandler(thread.getLooper());
}
public void registerListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void removeListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void startMeasuring() {
mHandler.startSamplingThread();
mLastTimeReading = SystemClock.elapsedRealtime();
}
public void stopMeasuring() {
mHandler.stopSamplingThread();
finalReadTrafficStats();
}
private void readTrafficStats() {
long newBytesUpStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileTxBytes() : TrafficStats.getTotalTxBytes()) * 1024;
long newBytesDownStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileRxBytes() : TrafficStats.getTotalRxBytes()) * 1024;
long byteDiffUpStream = newBytesUpStream - mPreviousUpStream;
long byteDiffDownStream = newBytesDownStream - mPreviousDownStream;
synchronized (this) {
long currentTime = SystemClock.elapsedRealtime();
double bandwidthUpStream = 0;
double bandwidthDownStream = 0;
if (mPreviousUpStream >= 0) {
bandwidthUpStream = (byteDiffUpStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mPreviousDownStream >= 0) {
bandwidthDownStream = (byteDiffDownStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mTrafficSpeedListener != null) {
mTrafficSpeedListener.onTrafficSpeedMeasured(bandwidthUpStream, bandwidthDownStream);
}
mLastTimeReading = currentTime;
}
mPreviousDownStream = newBytesDownStream;
mPreviousUpStream = newBytesUpStream;
}
private void finalReadTrafficStats() {
readTrafficStats();
mPreviousUpStream = -1;
mPreviousDownStream = -1;
}
private class SamplingHandler extends Handler {
private static final long SAMPLE_TIME = 1000;
private static final int MSG_START = 1;
private SamplingHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_START:
readTrafficStats();
sendEmptyMessageDelayed(MSG_START, SAMPLE_TIME);
break;
default:
throw new IllegalArgumentException("Unknown what=" + msg.what);
}
}
void startSamplingThread() {
sendEmptyMessage(SamplingHandler.MSG_START);
}
void stopSamplingThread() {
removeMessages(SamplingHandler.MSG_START);
}
}
public enum TrafficType {
MOBILE,
ALL
}
}
ITrafficSpeedListener.java
public interface ITrafficSpeedListener {
void onTrafficSpeedMeasured(double upStream, double downStream);
}
Utils.java
import java.util.Locale;
public class Utils {
private static final long B = 1;
private static final long KB = B * 1024;
private static final long MB = KB * 1024;
private static final long GB = MB * 1024;
public static String parseSpeed(double bytes, boolean inBits) {
double value = inBits ? bytes * 8 : bytes;
if (value < KB) {
return String.format(Locale.getDefault(), "%.1f " + (inBits ? "b" : "B") + "/s", value);
} else if (value < MB) {
return String.format(Locale.getDefault(), "%.1f K" + (inBits ? "b" : "B") + "/s", value / KB);
} else if (value < GB) {
return String.format(Locale.getDefault(), "%.1f M" + (inBits ? "b" : "B") + "/s", value / MB);
} else {
return String.format(Locale.getDefault(), "%.2f G" + (inBits ? "b" : "B") + "/s", value / GB);
}
}
}
.
Visual Result
It is feasible to obtain the transferred traffic amount using android.net.TrafficStats
. Here is an implementation of this idea which measures the up-stream and down-stream transfer rate. You can measure the rate of mobile network by passing TrafficSpeedMeasurer.TrafficType.MOBILE
to the TrafficSpeedMeasurer
constructor, otherwise using TrafficSpeedMeasurer.TrafficType.ALL
will result in measuring general traffic (WiFi/Mobile). Also by setting SHOW_SPEED_IN_BITS = true
in MainActivity
you can change the unit of speed measuring to bit
s per second.
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final boolean SHOW_SPEED_IN_BITS = false;
private TrafficSpeedMeasurer mTrafficSpeedMeasurer;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.connection_class);
mTrafficSpeedMeasurer = new TrafficSpeedMeasurer(TrafficSpeedMeasurer.TrafficType.ALL);
mTrafficSpeedMeasurer.startMeasuring();
}
@Override
protected void onDestroy() {
super.onDestroy();
mTrafficSpeedMeasurer.stopMeasuring();
}
@Override
protected void onPause() {
super.onPause();
mTrafficSpeedMeasurer.removeListener(mStreamSpeedListener);
}
@Override
protected void onResume() {
super.onResume();
mTrafficSpeedMeasurer.registerListener(mStreamSpeedListener);
}
private ITrafficSpeedListener mStreamSpeedListener = new ITrafficSpeedListener() {
@Override
public void onTrafficSpeedMeasured(final double upStream, final double downStream) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String upStreamSpeed = Utils.parseSpeed(upStream, SHOW_SPEED_IN_BITS);
String downStreamSpeed = Utils.parseSpeed(downStream, SHOW_SPEED_IN_BITS);
mTextView.setText("Up Stream Speed: " + upStreamSpeed + "n" + "Down Stream Speed: " + downStreamSpeed);
}
});
}
};
}
TrafficSpeedMeasurer.java
import android.net.TrafficStats;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
public class TrafficSpeedMeasurer {
private ITrafficSpeedListener mTrafficSpeedListener;
private SamplingHandler mHandler;
private TrafficType mTrafficType;
private long mLastTimeReading;
private long mPreviousUpStream = -1;
private long mPreviousDownStream = -1;
public TrafficSpeedMeasurer(TrafficType trafficType) {
mTrafficType = trafficType;
HandlerThread thread = new HandlerThread("ParseThread");
thread.start();
mHandler = new SamplingHandler(thread.getLooper());
}
public void registerListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void removeListener(ITrafficSpeedListener iTrafficSpeedListener) {
mTrafficSpeedListener = iTrafficSpeedListener;
}
public void startMeasuring() {
mHandler.startSamplingThread();
mLastTimeReading = SystemClock.elapsedRealtime();
}
public void stopMeasuring() {
mHandler.stopSamplingThread();
finalReadTrafficStats();
}
private void readTrafficStats() {
long newBytesUpStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileTxBytes() : TrafficStats.getTotalTxBytes()) * 1024;
long newBytesDownStream = (mTrafficType == TrafficType.MOBILE ? TrafficStats.getMobileRxBytes() : TrafficStats.getTotalRxBytes()) * 1024;
long byteDiffUpStream = newBytesUpStream - mPreviousUpStream;
long byteDiffDownStream = newBytesDownStream - mPreviousDownStream;
synchronized (this) {
long currentTime = SystemClock.elapsedRealtime();
double bandwidthUpStream = 0;
double bandwidthDownStream = 0;
if (mPreviousUpStream >= 0) {
bandwidthUpStream = (byteDiffUpStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mPreviousDownStream >= 0) {
bandwidthDownStream = (byteDiffDownStream) * 1.0 / (currentTime - mLastTimeReading);
}
if (mTrafficSpeedListener != null) {
mTrafficSpeedListener.onTrafficSpeedMeasured(bandwidthUpStream, bandwidthDownStream);
}
mLastTimeReading = currentTime;
}
mPreviousDownStream = newBytesDownStream;
mPreviousUpStream = newBytesUpStream;
}
private void finalReadTrafficStats() {
readTrafficStats();
mPreviousUpStream = -1;
mPreviousDownStream = -1;
}
private class SamplingHandler extends Handler {
private static final long SAMPLE_TIME = 1000;
private static final int MSG_START = 1;
private SamplingHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_START:
readTrafficStats();
sendEmptyMessageDelayed(MSG_START, SAMPLE_TIME);
break;
default:
throw new IllegalArgumentException("Unknown what=" + msg.what);
}
}
void startSamplingThread() {
sendEmptyMessage(SamplingHandler.MSG_START);
}
void stopSamplingThread() {
removeMessages(SamplingHandler.MSG_START);
}
}
public enum TrafficType {
MOBILE,
ALL
}
}
ITrafficSpeedListener.java
public interface ITrafficSpeedListener {
void onTrafficSpeedMeasured(double upStream, double downStream);
}
Utils.java
import java.util.Locale;
public class Utils {
private static final long B = 1;
private static final long KB = B * 1024;
private static final long MB = KB * 1024;
private static final long GB = MB * 1024;
public static String parseSpeed(double bytes, boolean inBits) {
double value = inBits ? bytes * 8 : bytes;
if (value < KB) {
return String.format(Locale.getDefault(), "%.1f " + (inBits ? "b" : "B") + "/s", value);
} else if (value < MB) {
return String.format(Locale.getDefault(), "%.1f K" + (inBits ? "b" : "B") + "/s", value / KB);
} else if (value < GB) {
return String.format(Locale.getDefault(), "%.1f M" + (inBits ? "b" : "B") + "/s", value / MB);
} else {
return String.format(Locale.getDefault(), "%.2f G" + (inBits ? "b" : "B") + "/s", value / GB);
}
}
}
.
Visual Result
edited Nov 30 '18 at 9:38
answered Nov 29 '18 at 12:33
aminographyaminography
6,29521534
6,29521534
This gives you the rate of all traffic over the network. This doesn't help you determine the upload rate of a particular HTTP request.
– Tim Malseed
Dec 2 '18 at 4:37
1
@TimMalseed: It is possible to measure traffic of a specific app usingTrafficStats.getUidTxBytes (int uid)
andTrafficStats.getUidRxBytes (int uid)
. You can see that the question mentioned a custom ROM namedResurrection Remix
which shows all traffic rate in status bar and he wants it according to: "as well as some custom ROMs". However, thank you for your down vote :)
– aminography
Dec 2 '18 at 5:09
Sure, but it's not possible to get the transfer rate of a particular HTTP request. Don't take it personally, it's just unfortunate that OP has not been very clear with the question and this is more of a compromise than a correct solution. I appreciate you detailing the possibilities ofTrafficStats
, and it is an interesting alternative. This answer is useful though, and doesn't deserve to be downvoted, so I apologise for that.
– Tim Malseed
Dec 2 '18 at 5:14
It's good to be aware answers like this one, I'm just wary of accepting and upvoting them as the 'correct' answer because it misleads less experienced developers. If the intention is to display the transfer rate of a particular upload to the user, and instead they display the transfer rate of all traffic, that's not technically correct, and could be wildly inaccurate depending on what else is going on on the device. What wasn't clear is OP was interested in simplicity over accuracy, which is understandable.
– Tim Malseed
Dec 2 '18 at 5:18
I agree with you, the intention of this question is a bit ambiguous. However if you bypass its title, I think above approach would be acceptable.
– aminography
Dec 2 '18 at 5:27
|
show 2 more comments
This gives you the rate of all traffic over the network. This doesn't help you determine the upload rate of a particular HTTP request.
– Tim Malseed
Dec 2 '18 at 4:37
1
@TimMalseed: It is possible to measure traffic of a specific app usingTrafficStats.getUidTxBytes (int uid)
andTrafficStats.getUidRxBytes (int uid)
. You can see that the question mentioned a custom ROM namedResurrection Remix
which shows all traffic rate in status bar and he wants it according to: "as well as some custom ROMs". However, thank you for your down vote :)
– aminography
Dec 2 '18 at 5:09
Sure, but it's not possible to get the transfer rate of a particular HTTP request. Don't take it personally, it's just unfortunate that OP has not been very clear with the question and this is more of a compromise than a correct solution. I appreciate you detailing the possibilities ofTrafficStats
, and it is an interesting alternative. This answer is useful though, and doesn't deserve to be downvoted, so I apologise for that.
– Tim Malseed
Dec 2 '18 at 5:14
It's good to be aware answers like this one, I'm just wary of accepting and upvoting them as the 'correct' answer because it misleads less experienced developers. If the intention is to display the transfer rate of a particular upload to the user, and instead they display the transfer rate of all traffic, that's not technically correct, and could be wildly inaccurate depending on what else is going on on the device. What wasn't clear is OP was interested in simplicity over accuracy, which is understandable.
– Tim Malseed
Dec 2 '18 at 5:18
I agree with you, the intention of this question is a bit ambiguous. However if you bypass its title, I think above approach would be acceptable.
– aminography
Dec 2 '18 at 5:27
This gives you the rate of all traffic over the network. This doesn't help you determine the upload rate of a particular HTTP request.
– Tim Malseed
Dec 2 '18 at 4:37
This gives you the rate of all traffic over the network. This doesn't help you determine the upload rate of a particular HTTP request.
– Tim Malseed
Dec 2 '18 at 4:37
1
1
@TimMalseed: It is possible to measure traffic of a specific app using
TrafficStats.getUidTxBytes (int uid)
and TrafficStats.getUidRxBytes (int uid)
. You can see that the question mentioned a custom ROM named Resurrection Remix
which shows all traffic rate in status bar and he wants it according to: "as well as some custom ROMs". However, thank you for your down vote :)– aminography
Dec 2 '18 at 5:09
@TimMalseed: It is possible to measure traffic of a specific app using
TrafficStats.getUidTxBytes (int uid)
and TrafficStats.getUidRxBytes (int uid)
. You can see that the question mentioned a custom ROM named Resurrection Remix
which shows all traffic rate in status bar and he wants it according to: "as well as some custom ROMs". However, thank you for your down vote :)– aminography
Dec 2 '18 at 5:09
Sure, but it's not possible to get the transfer rate of a particular HTTP request. Don't take it personally, it's just unfortunate that OP has not been very clear with the question and this is more of a compromise than a correct solution. I appreciate you detailing the possibilities of
TrafficStats
, and it is an interesting alternative. This answer is useful though, and doesn't deserve to be downvoted, so I apologise for that.– Tim Malseed
Dec 2 '18 at 5:14
Sure, but it's not possible to get the transfer rate of a particular HTTP request. Don't take it personally, it's just unfortunate that OP has not been very clear with the question and this is more of a compromise than a correct solution. I appreciate you detailing the possibilities of
TrafficStats
, and it is an interesting alternative. This answer is useful though, and doesn't deserve to be downvoted, so I apologise for that.– Tim Malseed
Dec 2 '18 at 5:14
It's good to be aware answers like this one, I'm just wary of accepting and upvoting them as the 'correct' answer because it misleads less experienced developers. If the intention is to display the transfer rate of a particular upload to the user, and instead they display the transfer rate of all traffic, that's not technically correct, and could be wildly inaccurate depending on what else is going on on the device. What wasn't clear is OP was interested in simplicity over accuracy, which is understandable.
– Tim Malseed
Dec 2 '18 at 5:18
It's good to be aware answers like this one, I'm just wary of accepting and upvoting them as the 'correct' answer because it misleads less experienced developers. If the intention is to display the transfer rate of a particular upload to the user, and instead they display the transfer rate of all traffic, that's not technically correct, and could be wildly inaccurate depending on what else is going on on the device. What wasn't clear is OP was interested in simplicity over accuracy, which is understandable.
– Tim Malseed
Dec 2 '18 at 5:18
I agree with you, the intention of this question is a bit ambiguous. However if you bypass its title, I think above approach would be acceptable.
– aminography
Dec 2 '18 at 5:27
I agree with you, the intention of this question is a bit ambiguous. However if you bypass its title, I think above approach would be acceptable.
– aminography
Dec 2 '18 at 5:27
|
show 2 more comments
What you're trying to determine is the transfer rate of the bytes being uploaded over your HTTP Client. Obviously, this depends on the HTTP client you're using.
There's no out-of-the-box solution which applies to all HTTP clients used on Android. The Android SDK does not provide any methods for you to determine the transfer rate of a particular upload.
Fortunately, you're using OKHttp and there is a relatively straight-forward way to do this. You're going to have to implement a custom RequestBody
, and observe the bytes being written to the buffer when the request is in flight.
There's a 'recipe' for doing this on the OkHttp Github:
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
You could also refer to this StackOverflow question dealing with the exact same topic:
Tracking progress of multipart file upload using OKHTTP
Another here:
OKHTTP 3 Tracking Multipart upload progress
Isn't this the same answer as mine?
– Murat Karagöz
Nov 29 '18 at 9:29
I don't think so, but we do both reference the same duplicate question. This question really should be closed, but OP has decided to use their bounty in order to prevent the question from being closed,
– Tim Malseed
Nov 29 '18 at 9:35
1
@PembaTamang you were asking for the upload rate of a particular HTTP request, but you've accepted an an answer which gives you the upload rate of ALL requests, even those uploads not started by your app.
– Tim Malseed
Dec 2 '18 at 4:39
add a comment |
What you're trying to determine is the transfer rate of the bytes being uploaded over your HTTP Client. Obviously, this depends on the HTTP client you're using.
There's no out-of-the-box solution which applies to all HTTP clients used on Android. The Android SDK does not provide any methods for you to determine the transfer rate of a particular upload.
Fortunately, you're using OKHttp and there is a relatively straight-forward way to do this. You're going to have to implement a custom RequestBody
, and observe the bytes being written to the buffer when the request is in flight.
There's a 'recipe' for doing this on the OkHttp Github:
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
You could also refer to this StackOverflow question dealing with the exact same topic:
Tracking progress of multipart file upload using OKHTTP
Another here:
OKHTTP 3 Tracking Multipart upload progress
Isn't this the same answer as mine?
– Murat Karagöz
Nov 29 '18 at 9:29
I don't think so, but we do both reference the same duplicate question. This question really should be closed, but OP has decided to use their bounty in order to prevent the question from being closed,
– Tim Malseed
Nov 29 '18 at 9:35
1
@PembaTamang you were asking for the upload rate of a particular HTTP request, but you've accepted an an answer which gives you the upload rate of ALL requests, even those uploads not started by your app.
– Tim Malseed
Dec 2 '18 at 4:39
add a comment |
What you're trying to determine is the transfer rate of the bytes being uploaded over your HTTP Client. Obviously, this depends on the HTTP client you're using.
There's no out-of-the-box solution which applies to all HTTP clients used on Android. The Android SDK does not provide any methods for you to determine the transfer rate of a particular upload.
Fortunately, you're using OKHttp and there is a relatively straight-forward way to do this. You're going to have to implement a custom RequestBody
, and observe the bytes being written to the buffer when the request is in flight.
There's a 'recipe' for doing this on the OkHttp Github:
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
You could also refer to this StackOverflow question dealing with the exact same topic:
Tracking progress of multipart file upload using OKHTTP
Another here:
OKHTTP 3 Tracking Multipart upload progress
What you're trying to determine is the transfer rate of the bytes being uploaded over your HTTP Client. Obviously, this depends on the HTTP client you're using.
There's no out-of-the-box solution which applies to all HTTP clients used on Android. The Android SDK does not provide any methods for you to determine the transfer rate of a particular upload.
Fortunately, you're using OKHttp and there is a relatively straight-forward way to do this. You're going to have to implement a custom RequestBody
, and observe the bytes being written to the buffer when the request is in flight.
There's a 'recipe' for doing this on the OkHttp Github:
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
You could also refer to this StackOverflow question dealing with the exact same topic:
Tracking progress of multipart file upload using OKHTTP
Another here:
OKHTTP 3 Tracking Multipart upload progress
answered Nov 28 '18 at 13:56
Tim MalseedTim Malseed
3,53733455
3,53733455
Isn't this the same answer as mine?
– Murat Karagöz
Nov 29 '18 at 9:29
I don't think so, but we do both reference the same duplicate question. This question really should be closed, but OP has decided to use their bounty in order to prevent the question from being closed,
– Tim Malseed
Nov 29 '18 at 9:35
1
@PembaTamang you were asking for the upload rate of a particular HTTP request, but you've accepted an an answer which gives you the upload rate of ALL requests, even those uploads not started by your app.
– Tim Malseed
Dec 2 '18 at 4:39
add a comment |
Isn't this the same answer as mine?
– Murat Karagöz
Nov 29 '18 at 9:29
I don't think so, but we do both reference the same duplicate question. This question really should be closed, but OP has decided to use their bounty in order to prevent the question from being closed,
– Tim Malseed
Nov 29 '18 at 9:35
1
@PembaTamang you were asking for the upload rate of a particular HTTP request, but you've accepted an an answer which gives you the upload rate of ALL requests, even those uploads not started by your app.
– Tim Malseed
Dec 2 '18 at 4:39
Isn't this the same answer as mine?
– Murat Karagöz
Nov 29 '18 at 9:29
Isn't this the same answer as mine?
– Murat Karagöz
Nov 29 '18 at 9:29
I don't think so, but we do both reference the same duplicate question. This question really should be closed, but OP has decided to use their bounty in order to prevent the question from being closed,
– Tim Malseed
Nov 29 '18 at 9:35
I don't think so, but we do both reference the same duplicate question. This question really should be closed, but OP has decided to use their bounty in order to prevent the question from being closed,
– Tim Malseed
Nov 29 '18 at 9:35
1
1
@PembaTamang you were asking for the upload rate of a particular HTTP request, but you've accepted an an answer which gives you the upload rate of ALL requests, even those uploads not started by your app.
– Tim Malseed
Dec 2 '18 at 4:39
@PembaTamang you were asking for the upload rate of a particular HTTP request, but you've accepted an an answer which gives you the upload rate of ALL requests, even those uploads not started by your app.
– Tim Malseed
Dec 2 '18 at 4:39
add a comment |
I am talking in the context of your app since this makes it easier to capture the real time speed of your uploaded data. You don't need any extra libraries or sdk api's.
You are presumably uploading the data in chunks to the server. So
a) You know the data size of each packet
b) You know the start time before sending the packet / before sending multiple packets
c) You know the end time of xy packets by the server response e.g. status 200
With that you have all parameters to calculate the upload speed
double uploadSpeed = packet.size / (endTime - startTime)
// time * 1000 to have it in seconds
EDIT:
Since you are using MultiPart
from OkHttp
you can monitor the amount of bytes uploaded. Tracking progress of multipart file upload using OKHTTP. You would replace packet.size
with the current uploaded amount and the endTime
would be an interval of xy seconds.
add a comment |
I am talking in the context of your app since this makes it easier to capture the real time speed of your uploaded data. You don't need any extra libraries or sdk api's.
You are presumably uploading the data in chunks to the server. So
a) You know the data size of each packet
b) You know the start time before sending the packet / before sending multiple packets
c) You know the end time of xy packets by the server response e.g. status 200
With that you have all parameters to calculate the upload speed
double uploadSpeed = packet.size / (endTime - startTime)
// time * 1000 to have it in seconds
EDIT:
Since you are using MultiPart
from OkHttp
you can monitor the amount of bytes uploaded. Tracking progress of multipart file upload using OKHTTP. You would replace packet.size
with the current uploaded amount and the endTime
would be an interval of xy seconds.
add a comment |
I am talking in the context of your app since this makes it easier to capture the real time speed of your uploaded data. You don't need any extra libraries or sdk api's.
You are presumably uploading the data in chunks to the server. So
a) You know the data size of each packet
b) You know the start time before sending the packet / before sending multiple packets
c) You know the end time of xy packets by the server response e.g. status 200
With that you have all parameters to calculate the upload speed
double uploadSpeed = packet.size / (endTime - startTime)
// time * 1000 to have it in seconds
EDIT:
Since you are using MultiPart
from OkHttp
you can monitor the amount of bytes uploaded. Tracking progress of multipart file upload using OKHTTP. You would replace packet.size
with the current uploaded amount and the endTime
would be an interval of xy seconds.
I am talking in the context of your app since this makes it easier to capture the real time speed of your uploaded data. You don't need any extra libraries or sdk api's.
You are presumably uploading the data in chunks to the server. So
a) You know the data size of each packet
b) You know the start time before sending the packet / before sending multiple packets
c) You know the end time of xy packets by the server response e.g. status 200
With that you have all parameters to calculate the upload speed
double uploadSpeed = packet.size / (endTime - startTime)
// time * 1000 to have it in seconds
EDIT:
Since you are using MultiPart
from OkHttp
you can monitor the amount of bytes uploaded. Tracking progress of multipart file upload using OKHTTP. You would replace packet.size
with the current uploaded amount and the endTime
would be an interval of xy seconds.
edited Nov 28 '18 at 12:07
answered Nov 28 '18 at 11:49
Murat KaragözMurat Karagöz
14.8k53568
14.8k53568
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393180%2fdetermine-transfer-rate-of-upload%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 9:33
Have you tried CellInfoGsm ?
– Sz-Nika Janos
Nov 28 '18 at 9:36
Maybe this library helps: github.com/facebook/network-connection-class
– leonardkraemer
Nov 28 '18 at 10:09
What do you use for uploading data (like Retrofit, a simple socket, etc.)?
– Gergely Kőrössy
Nov 28 '18 at 10:33
2
I am willing to give 200+ if I get an answer. Through a dummy question or something - better not tell the mods about that plan
– Tim Castelijns
Nov 28 '18 at 10:53