Android judges network speed

Judging the network speed on an Android device can be divided into two steps: obtaining the network type and measuring the network speed.

1. Get the network type

First, we need to check the type of network connection of the device, such as WiFi or mobile data. To achieve this functionality, we need to use ConnectivityManagerclasses. Please make sure to add the following permissions in AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Then use in code ConnectivityManagerto get the network connection type:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public String getNetworkType(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            return "WiFi";//wifi
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            return "Mobile";//蜂窝网络
        }
    }
    return "No connection";//没有网络连接
}

2. Measure network speed

Measuring network speed can be done by downloading or uploading a file. The following code demonstrates how to HttpURLConnectiondownload a file and calculate the download speed based on the download time and file size. Note that this needs to be done in a background thread to avoid blocking the UI thread.

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

public double measureDownloadSpeed(String urlToTest) {
    HttpURLConnection connection = null;
    InputStream inputStream = null;
    double speed = 0;
    try {
        URL url = new URL(urlToTest);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        int fileLength = connection.getContentLength();
        inputStream = connection.getInputStream();

        byte[] buffer = new byte[1024];
        long startTime = System.currentTimeMillis();
        int bytesRead;
        int totalBytesRead = 0;

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            totalBytesRead += bytesRead;
        }

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        if (duration > 0) {
            speed = (totalBytesRead * 8) / (duration * 1000); // Speed in Mbps
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return speed;
}

Then call the method in your code measureDownloadSpeed(), providing a file URL for testing. For example:

double downloadSpeed = measureDownloadSpeed("可以下载的网络资源");

Returns the download speed in Mbps. Note that actual measurements may be affected by network conditions, server response and other factors. for reference only.

In fact, I found this blog with <G><P><T>. There are so many contents, but I must improve the quality, so I will add some text here, hoping to make up enough numbers. Just go over there.

In fact, I found this blog with <G><P><T>. There are so many contents, but I must improve the quality, so I will add some text here, hoping to make up enough numbers. Just go over there.

In fact, I found this blog with <G><P><T>. There are so many contents, but I must improve the quality, so I will add some text here, hoping to make up enough numbers. Just go over there.

In fact, I found this blog with <G><P><T>. There are so many contents, but I must improve the quality, so I will add some text here, hoping to make up enough numbers. Just go over there.

Guess you like

Origin blog.csdn.net/mozushixin_1/article/details/129793958