This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now) in developing multilingual e-commerce platforms, and is summarized based on actual development practices. It mainly serves as a vehicle for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.
(I) Instant Messaging Functions
- Sending and Receiving Text Messages Use the network communication API of HarmonyOS Next (assuming it is the
net
module) to implement the sending and receiving of text messages. When the user enters a text message in the chat interface and clicks the send button, the view model layer obtains the message content and sends the message to the server through thenet
module. After the server receives the message, it pushes the message according to the recipient of the message. On the recipient's device, the application receives the message pushed by the server by listening to it, uses thenet
module to receive the message, and updates the chat record display in the view layer. For example:
import { net } from '@kit.NetworkKit';
// Function to send a text message
async function sendTextMessage(message: string, recipient: string): Promise<void> {
let request = net.createHttpRequest();
request.method = 'POST';
request.url = 'https://your-server-url/send-message';
request.headers = { 'Content-Type': 'application/json' };
request.requestBody = JSON.stringify({ message, recipient });
try {
await request.send();
if (request.responseCode === 200) {
console.log('Text message sent successfully.');
} else {
console.error('Text message sending failed, error code: ', request.responseCode);
}
} catch (error) {
console.error('Error occurred during text message sending: ', error);
}
}
// Function to receive a text message (assuming this function is called when the server pushes the message)
function receiveTextMessage(message: string): void {
// Update the chat record display in the view layer. Here, it is assumed that the view model layer provides a method to update the chat record, updateChatRecord().
viewModel.updateChatRecord(message);
}
-
Sending and Receiving Voice Messages
For voice messages, after obtaining the microphone permission, use the audio recording-related API (assuming it is the
audioRecorder
module) to record the voice. After the recording is completed, convert the audio data into a suitable format (such asmp3
), and then send it to the server through the network communication API. After the recipient receives the voice message, use the audio playing-related API (assuming it is theaudioPlayer
module) to play it. For example:
import { audioRecorder, audioPlayer } from '@kit.MediaKit';
import { net } from '@kit.NetworkKit';
// Function to record a voice message
async function recordVoiceMessage(): Promise<ArrayBuffer> {
let recorder = audioRecorder.createRecorder();
recorder.start();
// Assume the recording duration is set to 10 seconds
await new Promise(resolve => setTimeout(resolve, 10000));
recorder.stop();
let audioData = await recorder.getAudioData();
// Convert the audio data into the mp3 format (assuming there is a convertToMp3() method here for format conversion)
let mp3Data = convertToMp3(audioData);
return mp3Data;
}
// Function to send a voice message
async function sendVoiceMessage(recipient: string): Promise<void> {
let voiceData = await recordVoiceMessage();
let request = net.createHttpRequest();
request.method = 'POST';
request.url = 'https://your-server-url/send-voice-message';
request.headers = { 'Content-Type': 'audio/mp3' };
request.requestBody = voiceData;
try {
await request.send();
if (request.responseCode === 200) {
console.log('Voice message sent successfully.');
} else {
console.error('Voice message sending failed, error code: ', request.responseCode);
}
} catch (error) {
console.error('Error occurred during voice message sending: ', error);
}
}
// Function to receive a voice message and play it (assuming this function is called when the server pushes the message)
function receiveVoiceMessage(voiceData: ArrayBuffer): void {
let player = audioPlayer.createPlayer();
player.setDataSource(voiceData);
player.prepare();
player.start();
}
-
Sending and Receiving Image Messages
After taking a photo or selecting an image from the album, use the file reading API to read the image data, and then send the image data to the server through the network communication API. After the recipient receives the image message, use the image display-related API (such as the
Image
component) to display the image in the chat interface. For example:
import { fileIo } from '@kit.CoreFileKit';
import { net } from '@kit.NetworkKit';
// Function to send an image message
async function sendImageMessage(filePath: string, recipient: string): Promise<void> {
let fileContent = await fileIo.readFile(filePath);
let request = net.createHttpRequest();
request.method = 'POST';
request.url = 'https://your-server-url/send-image-message';
request.headers = { 'Content-Type': 'image/jpeg' };
request.requestBody = fileContent;
try {
await request.send();
if (request.responseCode === 200) {
console.log('Image message sent successfully.');
} else {
console.error('Image message sending failed, error code: ', deactivateDevice();
} catch (error) {
console.error('Error occurred during device deactivation: ', error);
}
}
// Function to receive an image message and display it (assuming this function is called when the server pushes the message)
function receiveImageMessage(fileContent: ArrayBuffer): void {
// Convert the image data into a format that can be used for display (such as ImageSource). Here, it is assumed that there is a convertToImageSource() method.
let imageSource = convertToImageSource(fileContent);
// Display the image in the chat interface. Here, it is assumed that the view layer provides a method to display the image, showImage().
view.showImage(imageSource);
}
(II) Location Service Functions
-
Obtaining the User's Current Location
As described previously, use the location control to obtain the user's current location information. When the user clicks the location sharing button, obtain the location information, including longitude and latitude, through the
geoLocationManager.getCurrentLocation()
method. For example:
import { geoLocationManager } from '@kit.LocationKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
// Function to obtain current location information
function getCurrentLocationInfo() {
const requestInfo: geoLocationManager.LocationRequest = {
'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
'scenario': geoLocationManager.LocationRequestScenario.UNSET,
'timeInterval': 1,
'distanceInterval': 0,
'maxAccuracy': 0
};
try {
geoLocationManager.getCurrentLocation(requestInfo)
.then((location: geoLocationManager.Location) => {
promptAction.showToast({ message: JSON.stringify(location) });
// Here, the obtained location information can be shared, such as sending it to a friend.
})
.catch((err: BusinessError) => {
console.error('Failed to obtain current location. Code is ', err.code, ', message is ', err.message);
});
} catch (err) {
console.error('Failed to obtain current location. Code is ', err.code, ', message is ', err.message);
}
}
-
Drawing Maps and Navigation (assuming integration with a third-party map library)
If you want to implement the functions of drawing maps and navigation in the application, you can integrate a third-party map library (such as Amap, Baidu Map, etc., which are supported by HarmonyOS Next). After obtaining the user's location information, pass the location information to the map library to display the location marker on the map. For example, using the API of the Amap library (assuming it is the
amap
module):
import { amap } from '@kit.MapKit';
// Display the user's location on the map
function showUserLocationOnMap(location: geoLocationManager.Location): void {
let map = amap.createMap('map-container');
let marker = amap.createMarker({
position: {
longitude: location.longitude,
latitude: location.latitude
}
});
map.addMarker(marker);
}
For the navigation function, according to the destination entered by the user and the current location, call the navigation interface of the map library to implement route planning and navigation guidance. For example:
// Navigate to the destination
async function navigateToDestination(destination: string): Promise<void> {
let currentLocation = await getCurrentLocationInfo();
let route = await amap.getRoute(currentLocation, destination);
amap.startNavigation(route);
}
(III) File Upload and Download Functions
- Uploading Photos When the user chooses to share a photo, in addition to sending an image message, you can also provide the function of uploading the photo to the server for storage or backup. Use the file reading API to read the photo data, and then upload the photo data to the server through the network communication API. For example:
import { fileIo } from '@kit.CoreFileKit';
import { net } from '@kit.NetworkKit';
// Function to upload a photo
async function uploadPhoto(filePath: string): Promise<void> {
let fileContent = await fileIo.readFile(filePath);
let request = net.createHttpRequest();
request.method = 'POST';
request.url = 'https://your-server-url/upload-photo';
request.headers = { 'Content-Type': 'image/jpeg' };
request.requestBody = fileContent;
try {
await request.send();
if (request.responseCode === 200) {
console.log('Photo uploaded successfully.');
} else {
console.error('Photo uploading failed, error code: ', request.responseCode);
}
} catch (error) {
console.error('Error occurred during photo uploading: ', error);
}
}
- Downloading Files (such as downloading chat record backups, etc.) If the application provides a download function, such as downloading a chat record backup file, use the network communication API to send a download request, receive the file data returned by the server, and use the file writing API to save the file to local. For example:
import { net } from '@kit.NetworkKit';
import { fileIo } from '@kit.CoreFileKit';
// Function to download a file
async function downloadFile(downloadUrl: string, savePath: string): Promise<void> {
let request = net.createHttpRequest();
request.method = 'GET';
request.url = downloadUrl;
try {
await request.send();
if (request.responseCode === 200) {
await fileIo.writeFile(savePath, request.responseData);
console.log('File downloaded successfully, save path: ', savePath);
} else {
console.error('File downloading failed, error code: ', request.responseCode);
}
} catch (error) {
console.error('Error occurred during file downloading: ', error);
}
}
IV. Summary and Outlook
Through this practical project, we have successfully built a social application based on the HarmonyOS Next system, covering core functions such as message sending, photo sharing, and location information sharing. During the development process, we have fully utilized key technologies such as the MVVM architecture, permission mechanism, security controls, location services, and network operations of HarmonyOS Next, ensuring the stability, security, and functionality of the application.
Looking ahead, with the continuous development and improvement of the HarmonyOS Next system and the increasingly perfect ecosystem, we can further expand the functions of social applications. For example, by combining the distributed technology of HarmonyOS Next, we can achieve a seamless social experience across devices, allowing users to freely switch between different devices and maintain the continuity of social interactions. At the same time, introducing more artificial intelligence technologies, such as intelligent friend recommendation and intelligent chatbots, can enhance the user experience and social fun. We hope that this article can provide useful references and inspirations for HarmonyOS Next developers and stimulate the development of more innovative applications, jointly building a prosperous HarmonyOS Next application ecosystem.
Top comments (0)