Android实时测网速功能,上传和下载速度

2,564 阅读3分钟

在Android中实现实时网络速度监控(包括上传速度和下载速度)可以通过以下几种方式实现:

  1. 使用TrafficStats类:TrafficStats类提供了一些静态方法,可以用于获取设备的网络流量数据。
  2. 使用第三方库:一些第三方库可以简化实现网络速度监控的过程。
  3. 实现自定义的网络速度测试:通过定期下载和上传数据来计算网络速度。

使用TrafficStats类

TrafficStats类可以提供应用的网络流量数据。我们可以通过定期采样来计算上传和下载速度。

代码示例

  1. 在Activity中定期更新网络速度
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView uploadSpeedTextView;
    private TextView downloadSpeedTextView;
    private Handler handler = new Handler();
    private long previousRxBytes = 0;
    private long previousTxBytes = 0;
    private long previousTimeStamp = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        uploadSpeedTextView = findViewById(R.id.uploadSpeedTextView);
        downloadSpeedTextView = findViewById(R.id.downloadSpeedTextView);

        previousRxBytes = TrafficStats.getTotalRxBytes();
        previousTxBytes = TrafficStats.getTotalTxBytes();
        previousTimeStamp = System.currentTimeMillis();

        handler.postDelayed(runnable, 1000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            long currentRxBytes = TrafficStats.getTotalRxBytes();
            long currentTxBytes = TrafficStats.getTotalTxBytes();
            long currentTimeStamp = System.currentTimeMillis();

            long rxBytesDelta = currentRxBytes - previousRxBytes;
            long txBytesDelta = currentTxBytes - previousTxBytes;
            long timeDelta = currentTimeStamp - previousTimeStamp;

            long rxSpeed = (rxBytesDelta * 1000) / timeDelta; // Bytes per second
            long txSpeed = (txBytesDelta * 1000) / timeDelta; // Bytes per second

            uploadSpeedTextView.setText("Upload Speed: " + txSpeed + " B/s");
            downloadSpeedTextView.setText("Download Speed: " + rxSpeed + " B/s");

            previousRxBytes = currentRxBytes;
            previousTxBytes = currentTxBytes;
            previousTimeStamp = currentTimeStamp;

            handler.postDelayed(this, 1000); // Update every second
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable); // Stop the handler when activity is destroyed
    }
}

  1. 布局文件(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">

    <TextView
        android:id="@+id/downloadSpeedTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download Speed: 0 B/s"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/uploadSpeedTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload Speed: 0 B/s"
        android:textSize="18sp"
        android:layout_marginTop="16dp" />

</LinearLayout>


使用第三方库

一些第三方库可以简化网络速度监控的实现,例如SpeedTest库。以下是如何使用这个库的示例:

  1. 添加依赖项

在build.gradle文件中添加SpeedTest库的依赖项:

dependencies {
    implementation 'com.github.anastr:speedviewlib:1.6.1'
}

  1. 使用SpeedTest库进行速度测试

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.github.anastr.speedviewlib.SpeedView;

public class MainActivity extends AppCompatActivity {

    private SpeedView downloadSpeedView;
    private SpeedView uploadSpeedView;
    private TextView downloadSpeedTextView;
    private TextView uploadSpeedTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadSpeedView = findViewById(R.id.downloadSpeedView);
        uploadSpeedView = findViewById(R.id.uploadSpeedView);
        downloadSpeedTextView = findViewById(R.id.downloadSpeedTextView);
        uploadSpeedTextView = findViewById(R.id.uploadSpeedTextView);

        // Initialize and start speed test here
    }
}

  1. 布局文件(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">

    <com.github.anastr.speedviewlib.SpeedView
        android:id="@+id/downloadSpeedView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:unit="B/s"
        android:withTremble="false" />

    <TextView
        android:id="@+id/downloadSpeedTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download Speed: 0 B/s"
        android:textSize="18sp"
        android:layout_marginTop="16dp" />

    <com.github.anastr.speedviewlib.SpeedView
        android:id="@+id/uploadSpeedView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:unit="B/s"
        android:withTremble="false"
        android:layout_marginTop="32dp" />

    <TextView
        android:id="@+id/uploadSpeedTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload Speed: 0 B/s"
        android:textSize="18sp"
        android:layout_marginTop="16dp" />

</LinearLayout>

自定义实现网络速度测试

你也可以实现一个自定义的网络速度测试,通过定期上传和下载数据来计算网络速度。下面是一个简单的示例:

  1. 实现网络速度测试
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private TextView downloadSpeedTextView;
    private TextView uploadSpeedTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadSpeedTextView = findViewById(R.id.downloadSpeedTextView);
        uploadSpeedTextView = findViewById(R.id.uploadSpeedTextView);

        new DownloadSpeedTestTask().execute("http://example.com/largefile");
    }

    private class DownloadSpeedTestTask extends AsyncTask<String, Void, Long> {
        @Override
        protected Long doInBackground(String... urls) {
            String urlStr = urls[0];
            long startTime = System.currentTimeMillis();
            long totalBytesRead = 0;
            try {
                URL url = new URL(urlStr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    totalBytesRead += bytesRead;
                }
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            long endTime = System.currentTimeMillis();
            long timeTakenMillis = endTime - startTime;
            return (totalBytesRead * 1000) / timeTakenMillis; // Bytes per second
        }

        @Override
        protected void onPostExecute(Long downloadSpeed) {
            downloadSpeedTextView.setText("Download Speed: " + downloadSpeed + " B/s");
            // You can implement similar logic for upload speed testing
        }
    }
}