HarmonyOS Development in Practice: In-Depth Analysis of Network Management Techniques and Practical Applications Based on API 11
Introduction:
In HarmonyOS project development, network management plays a crucial role. This article will delve into the core technologies of HarmonyOS network management based on API 11, helping developers accurately grasp network status and create smooth, user-friendly application experiences.
In HarmonyOS applications, real-time monitoring of network status is key to ensuring application stability and user experience. Changes in network status, such as switching from Wi-Fi to mobile data or from a connected state to a disconnected state, require the application to make corresponding adjustments. For example, the application can pause ongoing operations or alert users to ensure stable operation under various network conditions.
I. Real-Time Monitoring of Network Status for Intelligent Response to Changes
In HarmonyOS projects, building an efficient network management class is a core element in achieving a smooth application experience. This management class can monitor network status in real-time and respond quickly to changes in status. Next, we will discuss in detail how to design a network management class that meets professional requirements.
First, we define the callback function type for network connection status changes so that we can flexibly execute corresponding processing logic when the network status changes.
/**
* Type definition for network connection status change callback function
*/
export type NetworkStatusCallback = (status: NetworkType) => void;
Then, we use an enumeration type to define different network statuses, making the code clearer, more readable, and easier to maintain.
/**
* Enumeration: Network Type
* Used to identify the current network connection status
*/
export enum NetworkType {
STATE_NULL = 'NULL', // Indicates no network connection
UNKNOWN = 'UNKNOWN', // Unknown network type
MOBILE = 'MOBILE', // Mobile network
WIFI = 'WIFI', // Wi-Fi network
ETHERNET = 'ETHERNET' // Ethernet network (although typically not supported on mobile devices, it is retained for completeness)
}
/**
* Enumeration: Bearer Type (for internal use)
* Aligned with specific platform APIs to identify the bearer type of network connections
*/
enum BearerType {
MOBILE = 0,
WIFI = 1,
// ... Other possible bearer types, added according to platform APIs
ETHERNET = 3
}
Subsequently, we define some private variables to store the internal state information of the network management class, as well as a collection of callback functions for interaction with the outside world.
class LibNetworkStatus {
/**
* LibNetworkStatus singleton instance
* Ensures that there is only one network management class instance globally
*/
private static instance: LibNetworkStatus;
/**
* Current network status
* Stores the current network connection status
*/
private currentNetworkStatus: NetworkType = NetworkType.STATE_NULL;
/**
* Whether the network is available
* Indicates whether there is a currently available network connection
*/
private isNetworkAvailable: boolean = false;
/**
* HarmonyOS network connection object
* Used for interacting with the HarmonyOS system's network APIs
*/
private networkConnection?: Connection;
/**
* Collection of network connection status change callback functions
* When the network status changes, this collection will be iterated over and the corresponding callback functions will be called
*/
private callbacks: Set<NetworkStatusCallback> = new Set();
// The class's constructor, methods, and other logic implementations will continue here...
}
By defining these variables and callback method types, we have laid a solid foundation for the implementation of the network management class. Next, we will further implement core functions such as listening for network status changes, updating network status, and calling callback functions to notify the application. These implementations will ensure that our network management class can keep track of network status in real-time and accurately, and make corresponding handling based on status changes, thereby enhancing application stability and user experience.
II. Building Basic Callback Methods for Refined Callback Management
To ensure that our network management system can efficiently and accurately notify the application of network status changes, we need to build a comprehensive callback mechanism. This mechanism will allow the application to respond promptly to network status changes, thereby enhancing user experience.
/**
* Add callback method for listening to network status changes
*
* @param callback The callback function for listening to network status changes
* @param isCallBackCurrentNetworkStatus Whether to immediately call back and return the current network status
*/
addCallback(callback: NetworkStatusCallback, isCallBackCurrentNetworkStatus: boolean): void {
if (!callback || !this.callbacks) {
return;
}
// Ensure the callback method is not added repeatedly
if (this.callbacks.has(callback)) {
return;
}
this.callbacks.add(callback);
// If needed, immediately call back and return the current network status
if (isCallBackCurrentNetworkStatus) {
callback(this.currentNetworkStatus);
}
}
/**
* Remove the specified callback method
*
* @param callback The callback method to be removed
*/
removeCallback(callback: NetworkStatusCallback): void {
if (!callback || !this.callbacks || !this.callbacks.has(callback)) {
return;
}
this.callbacks.delete(callback);
}
/**
* Notify all registered callback methods of the current network status
*
* This method will be called when the network status changes to notify all registered callback methods
*/
callbackNetworkStatus(): void {
if (!this.callbacks || this.callbacks.size === 0) {
return;
}
// Iterate over all registered callback methods and call them, passing the current network status
this.callbacks.forEach(callback => {
callback(this.currentNetworkStatus);
});
}
Code Analysis:
Callback Method Addition and Removal: I defined two methods,
addCallback
andremoveCallback
, for adding and removing callback methods that listen to network status changes. This ensures the application's flexibility and extensibility, as the application can dynamically add or remove callbacks as needed during runtime.Callback Method Management: Using the
Set
data structure to manage callback methods ensures the uniqueness of callback methods, avoiding duplicate calls and potential memory leak issues.Immediate Callback Mechanism: In the
addCallback
method, we provide an optionisCallBackCurrentNetworkStatus
to allow immediate callback and return of the current network status when adding a callback. This is convenient for applications that need to know the current network status immediately.Status Notification: The
callbackNetworkStatus
method is responsible for notifying all registered callback methods when the network status changes. By iterating over each callback method in theSet
and calling them, we ensure that all interested parts of the application receive timely notifications of network status changes.
III. Core Network-Related Methods
- Obtaining Network Status Information
When building a network management class, providing a set of accurate and efficient network status acquisition methods is crucial. These methods allow us to monitor the network situation in real-time and take corresponding actions based on different network statuses. Next, we will introduce these core methods in detail.
/**
* Check if the current network is available
*
* @returns Returns a boolean indicating whether the current network is available
*/
isNetworkAvailable(): boolean {
return this.isNetworkAvailable;
}
/**
* Get the current network status
*
* @returns Returns the current network status code
*/
getCurrentNetworkStatus(): NetworkType {
return this.currentNetworkStatus;
}
- Accurate Detection and Acquisition of Current Network Type
/**
* Get the current network type
*
* This method obtains the current network status by calling the system API and determines the network type based on the bearer type.
* Through precise judgment logic, it ensures that the obtained network type is accurate.
*/
getDefaultNetSync () {
// Obtain the current network status
let netHandle = connection.getDefaultNetSync()
if (netHandle) {
let capabilities = connection.getNetCapabilitiesSync(netHandle)
LibLogManager.getLogger().debug(TAG,'getNetCapabilitiesSync:' + JSON.stringify(capabilities))
if (capabilities && capabilities.bearerTypes && capabilities.bearerTypes.length > 0) {
// Get the first bearer type
const bearerType = capabilities.bearerTypes[0];
// Determine the network type based on the bearer type
switch (bearerType) {
case BearerType.MOBILE.valueOf():
// Cellular network
this.currentNetworkStatus = NetworkType.MOBILE;
break;
case BearerType.WIFI.valueOf():
// Wi-Fi network
this.currentNetworkStatus = NetworkType.WIFI;
break;
case BearerType.ETHERNET.valueOf():
// Ethernet network (typically not supported on mobile devices, but retained for completeness)
this.currentNetworkStatus = NetworkType.ETHERNET;
break;
default:
// Unknown network type
this.currentNetworkStatus = NetworkType.UNKNOWN;
break;
}
}
}
}
Code Analysis:
- Using the
getNetCapabilitiesSync
method to obtain network capability information, including the list of bearer types.
- Registering to Listen for Mobile Network Status Changes
First, we need to understand the main types of network status changes: from no network to having a network, from having a network to no network, and switching from one network type to another (such as from Wi-Fi to cellular data). These status changes require the application to make corresponding adjustments, such as reloading data, pausing certain operations
Top comments (0)