24号直播公共事件和通知开发的课堂笔记 原创 精华

钟洪发老师
发布于 2021-6-24 21:59
浏览
8收藏

今晚要搞的事情:
公共事件:系统公共事件和自定义公共事件
通知:通知栏上显示的提醒信息

公共事件相关基础类:
24号直播公共事件和通知开发的课堂笔记-鸿蒙开发者社区
通知相关基础类:
24号直播公共事件和通知开发的课堂笔记-鸿蒙开发者社区
公共事件代码实现
第一步:发布公共事件,开发者可以发布四种公共事件:无序的公共事件、带权限的公共事件、有序的公共事件、粘性的公共事件。
第二步:订阅公共事件。
第三步:退订公共事件。
界面实现:

<Button
        ohos:id="$+id:subscribe_btn"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:text="订阅公共事件"
        ohos:text_size="20fp"
        ohos:text_color="#ffffff"
        ohos:background_element="#0000ff"
        ohos:layout_alignment="horizontal_center"
        ohos:top_padding="8vp"
        ohos:bottom_padding="8vp"
        ohos:left_padding="40vp"
        ohos:right_padding="40vp"
        ohos:top_margin="20vp"
        />
 <Button
        ohos:id="$+id:publish_btn"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:text="发布公共事件"
        ohos:text_size="20fp"
        ohos:text_color="#ffffff"
        ohos:background_element="#0000ff"
        ohos:layout_alignment="horizontal_center"
        ohos:top_padding="8vp"
        ohos:bottom_padding="8vp"
        ohos:left_padding="40vp"
        ohos:right_padding="40vp"
        ohos:top_margin="20vp"
        />

发布自定义无序的公共事件:

private void publishBtnFunc(Component component) {
    System.out.println("发布公共事件开始.....");
    //1.构建一个Intent对象,包含了自定义的事件的标识符
    Intent intent = new Intent();
    Operation oper = new Intent.OperationBuilder()
            .withAction("com.ybzy.demo.event")  //定义的事件的标识符
            .build();
    intent.setOperation(oper);
    
    //2.构建CommonEventData对象
    CommonEventData commonEventData = new CommonEventData(intent);
    
    //3.核心的发布事件的动作
    try {
        CommonEventManager.publishCommonEvent(commonEventData);
        System.out.println("发布公共事件完成.....");
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

订阅处理事件:

private void subscribeBtnFunc(Component component){
    if(!isSubscribed){
        System.out.println("订阅开始......");
        //1.构建MatchingSkills对象
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent("com.ybzy.demo.event");  //订阅者要订阅的具体事件
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON); //系统事件

        //2.构建订阅信息对象
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);

        //3.构建订阅者对象,对事件发生后的响应程序
        subscriber1st = new Subscriber1st(subscribeInfo);

        //4.核心动作接收事件
        try {
            CommonEventManager.subscribeCommonEvent(subscriber1st);
            //订阅完成
            isSubscribed = true;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }else{
        System.out.println("不能重复订阅!");
    }

}

自定义的订阅者对象:

public class Subsctriber1st extends CommonEventSubscriber {
    public Subsctriber1st(CommonEventSubscribeInfo subscribeInfo) {
        super(subscribeInfo);
    }

    EventRunner runner = EventRunner.create();
    EventHandler handler = new EventHandler(runner);

    //此放过就是事件发生后,回头的处理方法
    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {
         //写一个不耗时的处理代码
        System.out.println("不耗时的处理任务开始......" + commonEventData.getIntent().getAction());
        //现在的线程模式,是在主线程执行这个方法,所有耗时的任务是不能在主线程上执行的
        handler.postTask(new Runnable() {
            @Override
            public void run() {
                //耗时任务投递到异步子线程中来执行
                System.out.println("耗时的任务在这里执行........");
            }
        });

    }
}

退订公共事件:

@Override
protected void onStop() {
    super.onStop();
    try{
        CommonEventManager.unsubscribeCommonEvent(subscriber);
    }catch(RemoteException e) {
        System.out.println("Exception occurred during unsubscribeCommonEvent invocation.");
    }
}

发布带权限的公共事件:
带权限首先非系统已定义的权限,需要先在config.json中自定义,才可以申请使用。

"defPermissions": [
  {
    "name": "com.ybzy.demo.permission",
    "grantMode": "system_grant",
    "availableScope": "signature"
  }
],

发布事件的时候带上权限:

CommonEventPublishInfo publishInfo = new CommonEventPublishInfo();
String[] permissions = {"com.ybzy.demo.permission"};
publishInfo.setSubscriberPermissions(permissions); // 设置权限
CommonEventManager.publishCommonEvent(commonEventData,info);

订阅者也要配置申请上面我们自定义的权限:

"reqPermissions": [
  {
    "name": "com.ybzy.demo.permission",
    "reason": "get right",
    "usedScene": {
      "ability": [
        ".MainAbility"
      ],
      "when": "inuse"
    }
  }
]

发布有序的公共事件:
构造CommonEventPublishInfo对象,通过setOrdered(true)指定公共事件属性为有序公共事件,也可以指定一个最后的公共事件接收者。

publishInfo = new CommonEventPublishInfo();
publishInfo.setOrdered(true); // 设置属性为有序公共事件
eventData.setCode(1111);  //有序才能用
eventData.setData("dadaddaadfsadf");  //有序才能用

订阅处理事件:

CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
subscribeInfo.setPriority(100); // 设置优先级,优先级取值范围[-1000,1000],值默认为0。


final AsyncCommonEventResult result = goAsyncCommonEvent();
handler.postTask(new Runnable() {
    @Override
    public void run() {
        System.out.println("这里处理耗时的任务!");
        result.finishCommonEvent(); // 调用finish结束异步操作
    }
}

发布粘性的公共事件:
构造CommonEventPublishInfo对象,通过setSticky(true)指定公共事件属性为粘性公共事件。
发布者首先在config.json中申请发布粘性公共事件所需的权限

{
    "name": "ohos.permission.COMMONEVENT_STICKY",
    "reason": "Obtain the required permission",
    "usedScene": {
       "ability": [
        ".MainAbility"
       ],
       "when": "inuse"
}

发布粘性公共事件。

publishInfo = new CommonEventPublishInfo();
publishInfo.setSticky(true); //粘性的

通知代码实例:
界面实现:

<Button
    ohos:id="$+id:publish_notification_btn"
    ohos:text="发布通知"
    ohos:height="match_content"
    ohos:width="300vp"
    ohos:text_size="20fp"
    ohos:text_color="#ffffff"
    ohos:background_element="#0000ff"
    ohos:layout_alignment="horizontal_center"
    ohos:top_padding="8vp"
    ohos:bottom_padding="8vp"
    ohos:left_padding="40vp"
    ohos:right_padding="40vp"
    ohos:top_margin="20vp"
    />


<Button
    ohos:id="$+id:publish_cancel_btn"
    ohos:text="取消通知"
    ohos:height="match_content"
    ohos:width="300vp"
    ohos:text_size="20fp"
    ohos:text_color="#ffffff"
    ohos:background_element="#0000ff"
    ohos:layout_alignment="horizontal_center"
    ohos:top_padding="8vp"
    ohos:bottom_padding="8vp"
    ohos:left_padding="40vp"
    ohos:right_padding="40vp"
    ohos:top_margin="20vp"
    />

发布普通文本通知:
NO1.创建NotificationSlot,设置通知的震动,锁屏模式,重要级别等
NO2.构建NotificationRequest对象,绑定slot对象
NO3.调用request对象的setContent()设置通知的内容和类型
NO4.调用NotificationHelper的publishNotification()发布通知。

private void pubNotificationBtnFunc(Component component){
    //NO1.创建NotificationSlot,设置公共通知的震动,锁屏模式,重要级别等
    NotificationSlot slot = new NotificationSlot("slot_001", "slot_default", NotificationSlot.LEVEL_HIGH);
    slot.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC);
    slot.setEnableVibration(true); // 设置振动提醒
    //发布NotificationSlot对象,后面使用了才能起作用
    try {
        NotificationHelper.addNotificationSlot(slot);
    } catch (RemoteException ex) {
        System.out.println("Exception occurred during addNotificationSlot invocation.");
    }

    //NO2.构建NotificationRequest对象
    int notificationId = 0x1000001;
    NotificationRequest request = new NotificationRequest(notificationId);
    request.setSlotId(slot.getId());  //request和slot绑定,slot里的设置对这个通知生效
    //Image image = new Image(this);
    //image.setPixelMap(ResourceTable.Media_icon);
    //request.setBigIcon(image.getPixelMap());
    
    //Image image1 = new Image(this);
    //image1.setPixelMap(ResourceTable.Media_img);
    //request.setLittleIcon(image1.getPixelMap());
    
    //request.setShowDeliveryTime(true);  //通知后面显示时间

    //NO3.调用setContent()设置通知的内容
    NotificationRequest.NotificationNormalContent normalContent = new NotificationRequest.NotificationNormalContent();
    normalContent.setTitle("普通文本通知标题").setText("普通文本通知测试内容")
                .setAdditionalText("普通文本通知测试次要内容");
    NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(normalContent);
    request.setContent(notificationContent); // 设置通知的类型和内容

    //NO4.调用publishNotification()发布通知。
    try {
        NotificationHelper.publishNotification(request);
    } catch (RemoteException ex) {
        System.out.println("Exception occurred during publishNotification invocation.");
    }
}

取消通知
取消通知分为取消指定单条通知和取消所有通知,应用只能取消自己发布的通知。

cancelPublshBtn.setClickedListener(component -> {
    int notificationId = 0x100001;
    try {
        NotificationHelper.cancelNotification(notificationId);
    } catch (RemoteException ex) {
        System.out.println("Exception occurred during cancelNotification invocation.");
    }
});

取消所有通知:

cancelAllBtn.setClickedListener(component -> {
    try {
        NotificationHelper.cancelAllNotifications();
    } catch (RemoteException ex) {
        System.out.println("Exception occurred during cancelNotification invocation.");
    }

最后在玩儿个简单的点击通知跳转到新Ability:
意图代理相关基础类:
24号直播公共事件和通知开发的课堂笔记-鸿蒙开发者社区
实现简单的点击通知跳转打开一个PageAbility

//获取intentagent
private IntentAgent getIntentAgent() {
    Operation operation = new Intent.OperationBuilder().withDeviceId("")
            .withBundleName("com.ybzy.demo")
            .withAbilityName(AimAbility.class.getName())
            .build();
    Intent intent = new Intent();
    intent.setOperation(operation);
    List<Intent> intents = new ArrayList<>();
    intents.add(intent);
    IntentAgentInfo agentInfo = new IntentAgentInfo(
            REQUEST_CODE,  //private static final int REQUEST_CODE = 1000;  请求码
            IntentAgentConstant.OperationType.START_ABILITY,
            IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG,
            intents,
            new IntentParams()
    );
    IntentAgent agent = IntentAgentHelper.getIntentAgent(this, agentInfo);
    return agent;
}

通知中添加IntentAgent的代码示例如下:

private void publishLongTextFun(String longText){
    //NO2.构建NotificationRequest对象
    initNotifacationId(0x100002);
    //NO3.调用setContent()设置通知的内容
    NotificationRequest.NotificationLongTextContent content = new NotificationRequest.NotificationLongTextContent();
    content.setLongText(longText);
    NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
    request.setContent(notificationContent); // 设置通知的内容
    request.setIntentAgent(getIntentAgent()); //绑定到通知,绑定后,点击通知就会执行ntentAgent指定的动作
    try {
        NotificationHelper.publishNotification(request);
    } catch (RemoteException ex) {
        System.out.println("Exception occurred during publishNotification invocation.");
    }
}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
8
收藏 8
回复
举报
3条回复
按时间正序
/
按时间倒序
鸿联
鸿联

公共事件和通知可以用JS编程吗?

回复
2021-6-25 08:58:35
钟洪发老师
钟洪发老师 回复了 鸿联
公共事件和通知可以用JS编程吗?

现在还没看到可以!以后肯定会支持的!以后,js的技术线里开发app完全不用java的,但现在还不行!

回复
2021-6-25 20:22:19
topbox163
topbox163 回复了 鸿联
公共事件和通知可以用JS编程吗?
回复
2022-11-11 09:29:07
回复
    相关推荐