Android broadcastreceiver enables real-time monitoring of network status

Recently, in the company's project reconstruction, in order to improve the user experience, the project requires to add real-time monitoring of the current network state, so as to give user-friendly reminders and modify the UI interface when there is no network state. This paper will introduce the use of broadcastreceiver, one of the four components, to realize global network state monitoring and register in a dynamic way.

Registration method of broadcastreceiver:

(1) Dynamic registration: that is, use the registerreceiver () method to register in the code. Dynamic registration needs to be de registered in onpause or ondestory methods, otherwise it will be disclosed.

(2) Static registration: declare through the < receiver > tag under the application node of the manifest file, and the system will register automatically when it is started for the first time.

design sketch:

1. Define network status monitoring interface and method

/**
 * 网络状态类型改变的监听接口
 */
public interface NetStatusMonitor {
 void onNetChange(boolean netStatus);
}

/**
 * 设置网络状态监听接口
 */
public void setStatusMonitor(NetStatusMonitor netStatusMonitor) {
 this.netStatusMonitor = netStatusMonitor;
}

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
分享
二维码
< <上一篇
下一篇>>