Building Network, Database, and Notification Features in HarmonyOS Applications
Network Communication
The network module enables applications to perform HTTP requests, establish WebSocket connections, and manage socket-based data transfers.
Making HTTP Requetss
To initiate an HTTP request:
import http from '@ohos.net.http';
const client = http.createHttp();
client.request(
'http://localhost:3000/users',
{
method: http.RequestMethod.GET,
extraData: { param1: 'value1' }
}
)
.then((response: http.HttpResponse) => {
if (response.responseCode === 200) {
// Handle successful response
}
})
.catch((error: Error) => {
// Handle request failure
});
Request Configuration Options:
method: Specifies the HTTP method (GET, POST, PUT, DELETE).extraData: Request parameters, either a string or object.header: Custom headers sent with the request.connectTimeout: Connection timeout in milliseconds (default: 60,000).readTimeout: Read timeout in milliseconds (default: 60,000).
Response Data Structure:
responseCode: HTTP status code.header: Response headers.cookies: Returned cookies.result: Response body (typically JSON string).resultType: Type of returned data.
Using Axios for HTTP Operations
Install the axios library via ohpm:
ohpm install @ohos/axios
Ensure network permissions are granted in module.json5.
Import and use:
import axios from '@ohos/axios';
axios.get('url', {
params: { param1: 'value1' },
data: { param1: 'value1' }
})
.then(response => {
if (response.status !== 200) {
console.log('Request failed');
}
console.log('Request succeeded');
})
.catch(error => {
console.log('Request failed:', JSON.stringify(error));
});
Axios Response Properties:
status: HTTP status code.header: Response headers.data: Raw server response.
Data Storage
User Preferences (Key-Value Store)
Preferences provide lightweight, persistent key-value storage. Not suitable for complex relationships.
- Keys must be strings ≤80 bytes.
- Values as strings ≤8192 bytes.
- Load into memory; avoid storing more than 10,000 entries.
Initialize and manage:
import dataPreference from '@ohos.data.preferences';
dataPreference.getPreferences(this.context, 'MyAppPreference')
.then(preferences => {
// Success
})
.catch(reason => {
// Failure
});
Operations:
- Write:
preferences.put('key', value) .then(() => preferences.flush()) .catch(err => {}); - Delete:
preferences.delete('key') .then(() => {}) .catch(err => {}); - Read:
preferences.get('key', 'default') .then(value => console.log('Retrieved:', value)) .catch(err => console.log('Failed'));
Relational Database (RDB)
Uses SQLite for structured, relational data storage.
Initialize database:
import relationalStore from '@ohos.data.relationalStore';
const config = {
name: 'MyApplication.db',
securityLevel: relationalStore.SecurityLevel.S1
};
const createTableSql = `CREATE TABLE IF NOT EXISTS TASK (
ID INTEGER PRIMARY KEY,
NAME TEXT,
FINISHED BOOLEAN
)`;
relationalStore.getRdbStore(this.context, config, (err, store) => {
if (err) return;
store.executeSql(createTableSql);
});
CRUD Operations:
- Insert:
const task = { id: 1, name: 'Task', finished: false }; this.rdbStore.insert('TASK', task); - Update:
const updateData = { finished: true }; const predicates = new relationalStore.RdbPredicates('TASK'); predicates.equalTo('ID', 1); this.rdbStore.update(updateData, predicates); - Delete:
const predicates = new relationalStore.RdbPredicates('TASK'); predicates.equalTo('ID', 1); this.rdbStore.delete(predicates);
Query data:
const predicates = new relationalStore.RdbPredicates('TASK');
const result = await this.rdbStore.query(predicates, ['ID', 'NAME', 'FINISHED']);
const tasks: any[] = [];
while (!result.isAtLastRow) {
result.goToNextRow();
const id = result.getLong(result.getColumnIndex('ID'));
const name = result.getString(result.getColumnIndex('NAME'));
tasks.push({ id, name });
}
Notifications
Basic Notifications
Display alerts to users via the system notification bar.
import notification from '@ohos.notification';
const request: notification.NotificationRequest = {
id: 10,
content: {
contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'Notification Title',
text: 'Notification details',
additionalText: 'Extra info'
}
},
deliverTime: new Date().getTime(),
showDeliveryTime: true,
groupName: 'Messages',
slotType: notification.SlotType.SOCIAL_COMMUNICATION
};
notificationManager.publish(request)
.then(() => console.log('Published'))
.catch(err => console.log('Failed:', JSON.stringify(err)));
Slot Types:
SOCIAL_COMMUNICATION: Icon, sound, banner.SERVICE_INFORMATION: No banner.CONTENT_INFORMATION: Only icon.OTHER_TYPES: Minimal UI.
Content Types:
NOTIFICATION_CONTENT_BASIC_TEXT: Simple text.NOTIFICATION_CONTENT_LONG_TEXT: Extended text + summary.NOTIFICATION_CONTENT_MULTILINE: Multiple lines.NOTIFICATION_CONTENT_PICTURE: Includes image.
For images:
async aboutToAppear() {
const rm = getContext(this).resourceManager;
const file = await rm.getMediaContent($r('app.media.icon'));
image.createImageSource(file.buffer)
.createPixelMap()
.then(value => this.pixel = value)
.catch(err => console.log('Error loading image:', JSON.stringify(err)));
}
Cancel notifications:
notificationManager.cancel(10); // By ID
notificationManager.cancelAll(); // All notifications
Progress Bar Notifications
Show dynamic progress indicators (e.g., downloads):
this.isSupport = await notificationManager.isSupportTemplate('downloadTemplate');
if (!this.isSupport) return;
const template = {
name: 'downloadTemplate',
data: {
progressValue: this.progressValue,
progressMaxValue: 100
}
};
const request: notification.NotificationRequest = {
id: 999,
template,
content: {
contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: `${this.filename}: ${this.state}`,
text: '',
additionalText: `${this.progressValue}%`
}
}
};
Notification Intent Handling
Trigger actions when users tap notifications:
const wantInfo = {
wants: [
{
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility',
action: '',
entities: []
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
};
const agentInstance = await wantAgent.getWantAgent(wantInfo);
const request: notification.NotificationRequest = {
id: 999,
template,
wantAgent: agentInstance,
content: {
contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'Click to Open App',
text: ''
}
}
};
Notiifcations can launch abilities or broadcast events based on user interaction.