Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Building Network, Database, and Notification Features in HarmonyOS Applications

Notes 1

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.

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.