Android开发,写一段测试下载速度的代码
时间: 2024-02-18 12:00:59 浏览: 26
以下是一段测试下载速度的代码示例,使用了Android自带的DownloadManager来进行下载:
```java
public class DownloadSpeedTestActivity extends AppCompatActivity {
private static final String DOWNLOAD_URL = "http://speedtest.ftp.otenet.gr/files/test100k.db";
private DownloadManager downloadManager;
private long downloadId;
private TextView speedTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_speed_test);
speedTextView = findViewById(R.id.speedTextView);
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DOWNLOAD_URL));
downloadId = downloadManager.enqueue(request);
new Thread(new Runnable() {
@Override
public void run() {
boolean downloading = true;
long startTime = System.currentTimeMillis();
long bytesDownloaded = 0;
while (downloading) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
cursor.moveToFirst();
int bytesDownloadedIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
int bytesDownloadedCurrent = cursor.getInt(bytesDownloadedIndex);
if (bytesDownloadedCurrent != bytesDownloaded) {
long currentTime = System.currentTimeMillis();
long timeElapsed = currentTime - startTime;
double speed = (bytesDownloadedCurrent - bytesDownloaded) / (double)timeElapsed;
final String speedString = String.format(Locale.getDefault(), "%.2f KB/s", speed / 1024);
bytesDownloaded = bytesDownloadedCurrent;
runOnUiThread(new Runnable() {
@Override
public void run() {
speedTextView.setText(speedString);
}
});
}
int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(statusIndex);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
cursor.close();
}
}
}).start();
}
}
```
这段代码会启动一个下载任务,然后不断查询下载进度,计算下载速度,并将速度显示在界面上。请注意,这个示例仅供参考,实际应用中需要根据具体情况进行调整。