Android开发,写一段测试手机网络上传速度的代码
时间: 2024-02-18 09:01:06 浏览: 59
以下是一段测试手机网络上传速度的代码示例,使用了OkHttp库:
```java
public class UploadSpeedTestActivity extends AppCompatActivity {
private static final String UPLOAD_URL = "http://speedtest.ftp.otenet.gr/files/test100k.db";
private ProgressBar progressBar;
private TextView speedTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_speed_test);
progressBar = findViewById(R.id.progressBar);
speedTextView = findViewById(R.id.speedTextView);
new UploadTask().execute();
}
private class UploadTask extends AsyncTask<Void, Integer, Double> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setProgress(0);
speedTextView.setText("");
}
@Override
protected Double doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "test", RequestBody.create(MediaType.parse("application/octet-stream"), new byte[1024 * 100]))
.build();
Request request = new Request.Builder()
.url(UPLOAD_URL)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
long contentLength = response.body().contentLength();
InputStream inputStream = response.body().byteStream();
byte[] buffer = new byte[1024];
long bytesUploaded = 0;
int bytesRead;
long startTime = System.currentTimeMillis();
while ((bytesRead = inputStream.read(buffer)) != -1) {
bytesUploaded += bytesRead;
publishProgress((int) (bytesUploaded * 100 / contentLength));
}
inputStream.close();
response.body().close();
long endTime = System.currentTimeMillis();
double timeElapsed = (endTime - startTime) / 1000.0;
double speed = bytesUploaded / timeElapsed;
return speed;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
@Override
protected void onPostExecute(Double speed) {
super.onPostExecute(speed);
if (speed != null) {
String speedString = String.format(Locale.getDefault(), "%.2f KB/s", speed / 1024);
speedTextView.setText(speedString);
}
}
}
}
```
这段代码会向一个测试服务器上传一个100KB的文件,并计算上传速度,最后将速度显示在界面上。请注意,这个示例仅供参考,实际应用中需要根据具体情况进行调整。
阅读全文