Reputation: 1637
What would be best way to measure data usage in Android Xamarin app in Visual Studio?
I would like to know, how much data was transferred for each called request. I was looking in Xamarin Profiler but there isn't any info about data usage.
Thanks.
Upvotes: 3
Views: 1225
Reputation: 5182
One approach that you could use is via Android Device Monitor to watch network traffic
Alternatively you could wrap your request if you are using HttpClient
in a custom handler and log the size of the request payload:
public class RequestLoggerHandler : HttpClientHandler
{
#if DEBUG
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var stopwatch = Stopwatch.StartNew();
HttpResponseMessage response = null;
var headers = request.Headers;
var responseString = string.Empty;
var requestString = string.Empty;
var outputStringBuilder = new StringBuilder();
const string LINE_ENDING = "===================================================================================================";
const string SECTION_ENDING = "---------------------------------------------------------------------------------------------------";
try
{
if (request.Content != null) requestString = await request.Content?.ReadAsStringAsync();
response = await base.SendAsync(request, cancellationToken);
responseString = await response.Content?.ReadAsStringAsync();
outputStringBuilder.AppendLine(LINE_ENDING);
// Headers
outputStringBuilder.AppendLine("REQUEST HEADERS:");
foreach (var header in headers)
outputStringBuilder.AppendLine($"HEADER: {header.Key}: {header.Value?.ToList()?.FirstOrDefault()}");
outputStringBuilder.AppendLine(SECTION_ENDING);
// Parameters
outputStringBuilder.AppendLine("REQUEST PARAMS:");
outputStringBuilder.AppendLine(requestString);
outputStringBuilder.AppendLine(SECTION_ENDING);
// Response
outputStringBuilder.AppendLine("RESPONSE:");
outputStringBuilder.AppendLine(responseString);
outputStringBuilder.AppendLine(SECTION_ENDING);
return response;
}
finally
{
stopwatch.Stop();
var totalSize = 0L;
if (response != null)
{
var bodylength = response.Content.Headers.ContentLength;
var headerlength = response.Headers.ToString().Length;
totalSize = bodylength.GetValueOrDefault() + headerlength;
}
outputStringBuilder.AppendLine(string.Format("REQUEST [{0}:{1}] Time:{2}| Size:{3}| HTTP-CODE:{4}",
request.Method.ToString(),
request.RequestUri,
stopwatch.Elapsed.ToString("ss\\.fff"),
totalSize.ToPrettyByteSize(),
response?.StatusCode.ToString() ?? "No Internet Connectivity"));
outputStringBuilder.AppendLine(LINE_ENDING);
Debug.WriteLine("\n" + outputStringBuilder);
}
}
#endif
}
Then in your output window using VSColorOutput extension it produces a nice readable report of your request/response, including time and size. You can of cause simplify this code if all you are after is just the request/response size.
Upvotes: 3