HarmonyOS提供了应用的通知功能,即在应用外层通过使用应用图标进行一些事件的通知。常见的使用场景:
通知相关基础类包含NotificationSlot、NotificationRequest和NotificationHelper。基础类之间的关系如下所示:
图1 通知基础类关系图
NotificationSlot的级别目前支持如下几种, 由低到高:
- LEVEL_NONE: 表示通知不发布。
- LEVEL_MIN:表示通知可以发布,但是不显示在通知栏,不自动弹出,无提示音;该级别不适用于前台服务的场景。
- LEVEL_LOW:表示通知可以发布且显示在通知栏,不自动弹出,无提示音。
- LEVEL_DEFAULT:表示通知发布后可在通知栏显示,不自动弹出,触发提示音。
- LEVEL_HIGH:表示通知发布后可在通知栏显示,自动弹出,触发提示音。
具体的通知类型:目前支持六种类型,包括普通文本NotificationNormalContent、长文本NotificationLongTextContent、图片NotificationPictureContent、多行NotificationMultiLineContent、社交NotificationConversationalContent、媒体NotificationMediaContent。
通知的开发指导分为创建NotificationSlot、发布通知和取消通知等开发场景。
public static final String SLOT_ID = "high"; public static final String SLOT_NAME = "Order notification";//-------------------- .... @Overridepublic void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_main_ability_slice); ... defineNotificationSlot(Const.SLOT_ID, Const.SLOT_NAME, NotificationSlot.LEVEL_HIGH); ... }//---------------------private void defineNotificationSlot(String id, String name, int importance) { // 创建notificationSlot对象 NotificationSlot notificationSlot = new NotificationSlot(id, name, importance); // 设置振动提醒 notificationSlot.setEnableVibration(true); // 设置锁屏模式 notificationSlot.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC); Uri uri = Uri.parse(Const.SOUND_URI); notificationSlot.setSound(uri); try { NotificationHelper.addNotificationSlot(notificationSlot); } catch (RemoteException ex) { HiLog.error(LABEL_LOG, "%{public}s", "defineNotificationSlot remoteException."); } }
private void publishNotification(String title, String text) { //构建NotificationRequest对象,应用发布通知前,通过NotificationRequest的setSlotId()方法与NotificationSlot绑定,使该通知在发布后都具备该对象的特征 notificationId = 0x1000001; NotificationRequest request = new NotificationRequest(notificationId).setSlotId(Const.SLOT_ID) .setTapDismissed(true); //调用setContent()设置通知的内容 request.setContent(createNotificationContent(title, text)); IntentAgent intentAgent = createIntentAgent(MainAbility.class.getName(), IntentAgentConstant.OperationType.START_ABILITY); request.setIntentAgent(intentAgent); //调用publishNotification()发布通知 try { NotificationHelper.publishNotification(request); } catch (RemoteException ex) { HiLog.error(LABEL_LOG, "%{public}s", "publishNotification remoteException."); } }
取消通知分为取消指定单条通知和取消所有通知,应用只能取消自己发布的通知。
private void cancel() { try { NotificationHelper.cancelNotification(notificationId); } catch (RemoteException ex) { HiLog.error(LABEL_LOG, "%{public}s", "cancel remoteException."); } }
private void cancelAll() { try { NotificationHelper.cancelAllNotifications(); } catch (RemoteException ex) { HiLog.error(LABEL_LOG, "%{public}s", "cancelAll remoteException."); } }
|