Android checks network status through connectivity Manager

When developing Android applications, when it comes to network access, it is often necessary to check the network status to provide users with necessary reminders. You can usually do this through the connectivity manager. Connectivity manager has four main tasks: 1. Monitor mobile network status (including GPRS, WiFi, UMTS, etc.) 2. Send a broadcast when the mobile phone state changes. 3. Fail over when a network connection fails. 4. Provide the application with a high-precision and rough state that can obtain the available network. When we want to monitor the network state in the program, we only need the following steps:

1. Define a receiver overload onReceive function to complete the required functions, such as changing the appearance of the space according to whether WiFi and GPRS are disconnected

2, register Receiver in the right place, register in the program, and call the following functions in onCreate:

3, cancel the registration Receiver when appropriate, cancel it in the program, and call the following function in onDestroye:

PS: there are many ways to use telephonymanager on the Internet. The methods are as follows (but I have tried several times and have problems. For example, each time I enter an activity for the first time, I will automatically receive the signal of network disconnection. Each time the network state changes, I will receive multiple callbacks and the state is incorrect. I don't know what to pay attention to. Please give me some advice!)

As for the second method, I haven't tried it. The first method is better. If you want the program to be hidden in the background, it is recommended to open a service and register the broadcastreceiver in the service, but don't forget to cancel the registration. In the test, I encountered such a situation that a routing device currently connected to WiFi was turned off, but the program did not capture the unconnect network, which may be because the mobile device immediately connected to another routing device.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>