Programmatically Check the Network Speed in Android
Network speed can be defined as the total number of packets being exchanged by the client and the server per second, usually calculated in Megabits per second(Mbps). A bit is either a 0 or 1. 1 Megabit implies 1 Million bits. Usually, packet size depends on the protocol and various other factors and usually ranges on a vast scale. In this article, a program is implemented that fetches us Upload and Download speeds with the server. Note that the program is successful when the device is connected to a network.
This program could be used for research as well as for optimization:
- Research: one could derive the content and the available speeds to correlate the network dependency.
- Optimization: one could continuously monitor the speed and context, to avoid the connection when not required or reduce the quality of a video being broadcasted depending upon the current speeds.
Step 1: Create an Empty activity in Android Studio. To create one, follow this article- https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/. Check if the primary language selected is Kotlin.
Step 2: Go to the AndroidManifest.xml file and add the uses-permission ACCESS_NETWORK_STATE.
Step 3: In the activity_main.xml, add a button. Bellow is the code for the same.
Step 4: In the MainActivity.kt, add the below code. setOnClickListener is added with the button, which when clicked shows the upload speed and download speed as a toast on the screen.