Android uses observer mode Observer to monitor network status
- 2021-09-11 21:28:58
- OfStack
In the development process of Android, it is often used to judge the current network status and make corresponding responses when the network status changes. If you want to monitor the network status, it is more appropriate to use the observer mode, without saying much nonsense, just go to the code.
The observer pattern belongs to one of the 23 object-oriented design patterns. If you don't understand it, please use your own Google
Since the observer mode is used, it is naturally inseparable from the two most important classes Subject and Ovserver in the observer mode
Subjcet interface:
/**
* Description: observer subject
* author: Wang
* date: 11/28/16 11:19 AM
*
* Copyright©2016 by wang. All rights reserved.
*/
public interface NetConnectionSubject {
/**
* Registered observer
*
* @param observer
*/
public void addNetObserver(NetConnectionObserver observer);
/**
* Remove Observer
*
* @param observer
*/
public void removeNetObserver(NetConnectionObserver observer);
/**
* Status update notification
*
* @param type
*/
public void notifyNetObserver(int type);
}
Observer interface:
/**
* Description: observer
* author: Wang
* date: 11/28/16 11:20 AM
*
* Copyright©2016 by wang. All rights reserved.
*/
public interface NetConnectionObserver {
/**
* Notify the observer to change the status
*
* @param type
*/
public void updateNetStatus(int type);
}
In Android, the best way to implement the Subject class is Application, because it is globally only 1 and its life cycle is the life cycle of this App:
/**
* Description: App's application should extend this class
* author: Wang
* date: 11/28/16 10:34 AM
*
* Copyright©2016 by wang. All rights reserved.
*/
public abstract class BaseApplication extends Application implements NetConnectionSubject {
protected static BaseApplication instance;
private int currentNetType = -1;
private List<NetConnectionObserver> observers = new ArrayList<>();
public static BaseApplication getInstance() {
return instance;
}
/**
* current net connection type
*
* @return
*/
public int getCurrentNetType() {
return currentNetType;
}
/**
* current net connection status
*
* @return
*/
public boolean isNetConnection() {
return currentNetType == NetWorkUtil.NET_NO_CONNECTION ? false : true;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
currentNetType = NetWorkUtil.getConnectionType(this);
}
@Override
public void addNetObserver(NetConnectionObserver observer) {
if (!observers.contains(observer)) {
observers.add(observer);
}
}
@Override
public void removeNetObserver(NetConnectionObserver observer) {
if (observers != null && observers.contains(observer)) {
observers.remove(observer);
}
}
@Override
public void notifyNetObserver(int type) {
/**
* Avoid sending the same network state multiple times
*/
if (currentNetType == type) {
return;
} else {
currentNetType = type;
if (observers != null && observers.size() > 0) {
for (NetConnectionObserver observer : observers) {
observer.updateNetStatus(type);
}
}
}
}
}
Whoever wants to implement the Observer interface depends on the specific scene. Here, take Activity as the chestnut:
/**
* Description: TODO
* author: WangKunHui
* date: 16/12/30 Afternoon 3:08
* <p>
* Copyright©2016 by wang. All rights reserved.
*/
public class TestActivity extends Activity implements NetConnectionObserver {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Omission 1 Some methods **/
BaseApplication.getInstance().addNetObserver(this);
}
@Override
public void updateNetStatus(int type) {
// When the state of the listening network changes, We will receive feedback in time here
}
@Override
protected void onDestroy() {
super.onDestroy();
BaseApplication.getInstance().removeNetObserver(this);
}
}
Here is a place 1 must note: When Activity is destroyed, 1 must remove this observer from the observer queue! Otherwise, a memory leak will occur
At this point, the observer mode has been written. Thank you for watching.
Reader: Have you forgotten something about network monitoring?
Me: Easy easy ~ It was just half-time
If there are only so many above, you can't monitor the network status. If you want to monitor the changes of the network status, you have to rely on our broadcast recipients. Please welcome:
/**
* Description: Monitoring of network connection status
* author: Wang
* date: 16/8/3 Afternoon 10:54
*
* Copyright©2016 by wang. All rights reserved.
*/
public class NetConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
int connectionType = NetWorkUtil.getConnectionType(context);
/**
* Change network status
*/
if (BaseApplication.getInstance() != null) {
BaseApplication.getInstance().notifyNetObserver(connectionType);
}
}
}
}
NetWorkUtil:
/**
* @author Wang
* @version 1.0.0
* @description Network operation tool class
* @create 2014-2-18 Morning 09:22:30
* @company
*/
public class NetWorkUtil {
/**
* No network link
*/
public static final int NET_NO_CONNECTION = 0;
/**
* wifi
*/
public static final int NET_TYPE_WIFI = 1;
public static final int NET_TYPE_2G = 2;
public static final int NET_TYPE_3G = 3;
public static final int NET_TYPE_4G = 4;
/**
* Unknown network type
*/
public static final int NET_TYPE_UNKNOWN = 5;
/**
* Get Network Type
*
* @param context
* @return
*/
public static int getConnectionType(Context context) {
int netType = NET_NO_CONNECTION;
NetworkInfo networkInfo = ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (networkInfo == null) {
netType = NET_NO_CONNECTION;
} else {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
netType = NET_TYPE_WIFI;
} else {
int networkType = networkInfo.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
netType = NET_TYPE_2G;
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9:replace by 14
case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11:replace by 12
case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13:replace by 15
netType = NET_TYPE_3G;
break;
case TelephonyManager.NETWORK_TYPE_LTE: //api<11:replace by 13
netType = NET_TYPE_4G;
break;
default:
String subType = networkInfo.getSubtypeName();
if (subType.equalsIgnoreCase("TD-SCDMA") ||
subType.equalsIgnoreCase("WCDMA") ||
subType.equalsIgnoreCase("CDMA2000")) {
netType = NET_TYPE_3G;
} else {
netType = NET_TYPE_UNKNOWN;
}
break;
}
}
}
return netType;
}
}
Ok, at this point, all the contents on the title have been written. Finally, don't forget the permissions and register the broadcast recipients.