自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

HarmonyOS 基礎(chǔ)技術(shù)賦能之公共事件(CommonEvent)開發(fā)

開發(fā) 前端 OpenHarmony
系統(tǒng)將收集到的事件信息,根據(jù)系統(tǒng)策略發(fā)送給訂閱該事件的用戶程序。 公共事件包括:終端設(shè)備用戶可感知的亮滅屏事件,以及系統(tǒng)關(guān)鍵服務(wù)發(fā)布的系統(tǒng)事件(例如:USB插拔,網(wǎng)絡(luò)連接,系統(tǒng)升級)等。

[[423584]]

想了解更多內(nèi)容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)

https://harmonyos.51cto.com

引言

在HarmonyOS通過CES(Common Event Service,公共事件服務(wù))為應(yīng)用程序提供訂閱、發(fā)布、退訂公共事件的能力。

公共事件可分為系統(tǒng)公共事件和自定義公共事件。

系統(tǒng)公共事件:系統(tǒng)將收集到的事件信息,根據(jù)系統(tǒng)策略發(fā)送給訂閱該事件的用戶程序。 公共事件包括:終端設(shè)備用戶可感知的亮滅屏事件,以及系統(tǒng)關(guān)鍵服務(wù)發(fā)布的系統(tǒng)事件(例如:USB插拔,網(wǎng)絡(luò)連接,系統(tǒng)升級)等。

自定義公共事件:應(yīng)用自定義一些公共事件用來處理業(yè)務(wù)邏輯。

場景介紹

每個應(yīng)用都可以訂閱自己感興趣的公共事件,訂閱成功后且公共事件發(fā)布后,系統(tǒng)會把其發(fā)送給應(yīng)用。這些公共事件可能來自系統(tǒng)、其他應(yīng)用和應(yīng)用自身。HarmonyOS提供了一套完整的API,支持用戶訂閱、發(fā)布和接收公共事件。發(fā)布公共事件需要借助CommonEventData對象,接收公共事件需要繼承CommonEventSubscriber類并實現(xiàn)onReceiveEvent回調(diào)函數(shù)。

開發(fā)者可以發(fā)布四種公共事件:無序的公共事件、帶權(quán)限的公共事件、有序的公共事件、粘性的公共事件。

本文主講無序的公共事件,其他類型事件,可參考華為官方開發(fā)文檔學(xué)習(xí)。

指南

1.發(fā)布公共事件:

  1. try { 
  2.   Intent intent = new Intent(); 
  3.   Operation operation = new Intent.OperationBuilder() 
  4.       .withAction(“my.action”)//自定義字符串類型的action 
  5.       .build(); 
  6.   intent.setOperation(operation); 
  7.   intent.setParam("result","commonEventData"); 
  8.   intent.setParam("isCommonEvent",true); 
  9.   CommonEventData eventData = new CommonEventData(intent); 
  10.   CommonEventManager.publishCommonEvent(eventData); 
  11.   LogUtils.info(TAG,"PublishCommonEvent SUCCESS"); 
  12. } catch (RemoteException e) { 
  13.   LogUtils.error(TAG,"Exception occurred during publishCommonEvent invocation."); 

2. 訂閱公共事件

1)創(chuàng)建CommonEventSubscriber派生類,在onReceiveEvent()回調(diào)函數(shù)中處理公共事件。

  1. private class MyCommonEventSubscriber extends CommonEventSubscriber { 
  2.     MyCommonEventSubscriber(CommonEventSubscribeInfo info) { 
  3.      super(info); 
  4.  } 
  5.  
  6.  @Override 
  7.  public void onReceiveEvent(CommonEventData commonEventData) { 

2)構(gòu)造MyCommonEventSubscriber對象,調(diào)用CommonEventManager. subscribeCommonEvent()接口進(jìn)行訂閱。

  1. MatchingSkills matchingSkills = new MatchingSkills(); 
  2. //添加自定義的ation 
  3. matchingSkills.addEvent(ACTION);  
  4. matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BOOT_COMPLETED); // 開機(jī)完成事件 
  5. matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_CHARGING); // 正在充電事件 
  6. CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills); 
  7. subscriber = new MyCommonEventSubscriber(subscribeInfo); 
  8. try { 
  9.   CommonEventManager.subscribeCommonEvent(subscriber); 
  10.   LogUtils.info(TAG,"SubscribeCommonEvent SUCCESS"); 
  11. } catch (RemoteException e) { 
  12.   LogUtils.error(TAG,"Exception occurred during subscribeCommonEvent invocation."); 

3)針對在onReceiveEvent中不能執(zhí)行耗時操作的限制,可以使用CommonEventSubscriber的goAsyncCommonEvent()來實現(xiàn)異步操作,函數(shù)返回后仍保持該公共事件活躍,且執(zhí)行完成后必須調(diào)用。

  1. // EventRunner創(chuàng)建新線程,將耗時的操作放到新的線程上執(zhí)行 
  2.  private EventRunner eventRunner=EventRunner.create(); 
  3.  
  4. // MyEventHandler為EventHandler的派生類,在不同線程間分發(fā)和處理事件和Runnable任務(wù) 
  5.  private MyEventHandle myEventHandle=new MyEventHandle(eventRunner); 
  6.  
  7.  private class MyCommonEventSubscriber extends CommonEventSubscriber { 
  8.      MyCommonEventSubscriber(CommonEventSubscribeInfo info) { 
  9.       super(info); 
  10.   } 
  11.   @Override 
  12.   public void onReceiveEvent(CommonEventData commonEventData) { 
  13.         //以下為如果有耗時操作時,執(zhí)行的代碼 
  14.         final AsyncCommonEventResult result = goAsyncCommonEvent(); 
  15.         Runnable runnable=new Runnable() { 
  16.          @Override 
  17.          public void run() { 
  18.            // 待執(zhí)行的操作,由開發(fā)者定義 
  19.            myEventHandle.sendEvent(100); 
  20.  
  21.            result.finishCommonEvent(); // 調(diào)用finish結(jié)束異步操作 
  22.          } 
  23.        }; 
  24.        myEventHandle.postTask(runnable); 
  25.   } 
  26.  
  27.  private class MyEventHandle extends EventHandler{ 
  28.  
  29.   public MyEventHandle(EventRunner runner) throws IllegalArgumentException { 
  30.     super(runner); 
  31.   } 
  32.  
  33.    @Override 
  34.    protected void processEvent(InnerEvent event) { 
  35.      super.processEvent(event); 
  36.      //處理事件,由開發(fā)者撰寫 
  37.      int evnetID=event.eventId; 
  38.      LogUtils.info(TAG,"evnetID:"+evnetID); 
  39.  
  40.    } 
  41.  } 

3. 退訂公共事件:

  1.  //在Ability的onStop()中調(diào)用CommonEventManager.unsubscribeCommonEvent()方法來退訂公共事件。調(diào)用后,之前訂閱的所有公共事件均被退訂。 
  2.    @Override 
  3. protected void onStop() { 
  4.   super.onStop(); 
  5.   try { 
  6.     CommonEventManager.unsubscribeCommonEvent(subscriber); 
  7.     LogUtils.info(TAG, "unsubscribeCommonEvent success."); 
  8.   } catch (RemoteException e) { 
  9.     LogUtils.error(TAG, "Exception occurred during unsubscribeCommonEvent invocation."); 
  10.   } 

實現(xiàn)效果

1.啟動APP時,如下圖:

HarmonyOS 基礎(chǔ)技術(shù)賦能之 公共事件(CommonEvent)開發(fā)-鴻蒙HarmonyOS技術(shù)社區(qū)

2. 先點擊“訂閱公共事件”,后點擊“發(fā)布無序公共事件”。打印的log:

  1. 09-02 10:31:07.693 10390-10390/com.zel.commoneventdemo I 00000/LogUtil: MainAbilitySlice: SubscribeCommonEvent SUCCESS 
  2. 09-02 10:31:09.795 10390-10390/com.zel.commoneventdemo I 00000/LogUtil: MainAbilitySlice: PublishCommonEvent SUCCESS 
  3. 09-02 10:31:09.798 10390-10390/com.zel.commoneventdemo I 00000/LogUtil: MainAbilitySlice: action:action.send.message/result:commonEventData/isCommonEvent:true 
  4. 09-02 10:31:09.799 10390-12455/com.zel.commoneventdemo I 00000/LogUtil: MainAbilitySlice: evnetID:100    

附上源碼

1.MainAbilitySlice

  1. public class MainAbilitySlice extends AbilitySlice implements ClickedListener { 
  2.   private String TAG="MainAbilitySlice"
  3.   private MyCommonEventSubscriber subscriber; 
  4.   private static final String ACTION="action.send.message"
  5.  
  6.   @Override 
  7.   public void onStart(Intent intent) { 
  8.     super.onStart(intent); 
  9.     super.setUIContent(ResourceTable.Layout_ability_main); 
  10.     Button btPublisher=(Button)findComponentById(ResourceTable.Id_btPublisher); 
  11.     Button btSubscriber=(Button)findComponentById(ResourceTable.Id_btSubscriber); 
  12.     btPublisher.setClickedListener(this); 
  13.     btSubscriber.setClickedListener(this); 
  14.   } 
  15.  
  16.   @Override 
  17.   public void onActive() { 
  18.     super.onActive(); 
  19.   } 
  20.  
  21.   @Override 
  22.   public void onForeground(Intent intent) { 
  23.     super.onForeground(intent); 
  24.   } 
  25.  
  26.   @Override 
  27.   public void onClick(Component component) { 
  28.     switch (component.getId()){ 
  29.       case ResourceTable.Id_btPublisher: 
  30.         try { 
  31.           Intent intent = new Intent(); 
  32.           Operation operation = new Intent.OperationBuilder() 
  33.               .withAction(ACTION
  34.               .build(); 
  35.           intent.setOperation(operation); 
  36.           intent.setParam("result","commonEventData"); 
  37.           intent.setParam("isCommonEvent",true); 
  38.           CommonEventData eventData = new CommonEventData(intent); 
  39.           CommonEventManager.publishCommonEvent(eventData); 
  40.           LogUtils.info(TAG,"PublishCommonEvent SUCCESS"); 
  41.         } catch (RemoteException e) { 
  42.           LogUtils.error(TAG,"Exception occurred during publishCommonEvent invocation."); 
  43.         } 
  44.         break; 
  45.       case ResourceTable.Id_btSubscriber: 
  46.         MatchingSkills matchingSkills = new MatchingSkills(); 
  47.         //添加自定義的ation 
  48.         matchingSkills.addEvent(ACTION);//自定義事件 
  49.         matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BOOT_COMPLETED); // 開機(jī)完成事件 
  50.         matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_CHARGING); // 正在充電事件 
  51.         CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills); 
  52.         subscriber = new MyCommonEventSubscriber(subscribeInfo); 
  53.         try { 
  54.           CommonEventManager.subscribeCommonEvent(subscriber); 
  55.           LogUtils.info(TAG,"SubscribeCommonEvent SUCCESS"); 
  56.         } catch (RemoteException e) { 
  57.           LogUtils.error(TAG,"Exception occurred during subscribeCommonEvent invocation."); 
  58.         } 
  59.         break; 
  60.     } 
  61.  
  62.   } 
  63.    //// EventRunner創(chuàng)建新線程,將耗時的操作放到新的線程上執(zhí)行 
  64.    private EventRunner eventRunner=EventRunner.create(); 
  65.  
  66.   // MyEventHandler為EventHandler的派生類,在不同線程間分發(fā)和處理事件和Runnable任務(wù) 
  67.    private MyEventHandle myEventHandle=new MyEventHandle(eventRunner); 
  68.  
  69.    private class MyCommonEventSubscriber extends CommonEventSubscriber { 
  70.        MyCommonEventSubscriber(CommonEventSubscribeInfo info) { 
  71.         super(info); 
  72.     } 
  73.  
  74.      /** 
  75.       * 針對在onReceiveEvent中不能執(zhí)行耗時操作的限制,可以使用CommonEventSubscriber的goAsyncCommonEvent()來實現(xiàn)異步操作, 
  76.       * 函數(shù)返回后仍保持該公共事件活躍,且執(zhí)行完成后必須調(diào)用AsyncCommonEventResult.finishCommonEvent()來結(jié)束。 
  77.       * @param commonEventData 
  78.       */ 
  79.     @Override 
  80.     public void onReceiveEvent(CommonEventData commonEventData) { 
  81.           //非執(zhí)行耗時操作,以下代碼即可 
  82.           Intent intent=commonEventData.getIntent(); 
  83.           String action= intent.getAction(); 
  84.           switch (action){ 
  85.             //自定義事件 
  86.             case ACTION
  87.               String result=intent.getStringParam("result"); 
  88.               boolean isCommonEventData=intent.getBooleanParam("isCommonEvent",false); 
  89.               LogUtils.info(TAG,"action:"+action+"/result:"+result+"/isCommonEvent:"+isCommonEventData); 
  90.               break; 
  91.             // 開機(jī)完成事件 
  92.             case CommonEventSupport.COMMON_EVENT_BOOT_COMPLETED: 
  93.               LogUtils.info(TAG,"action:"+action); 
  94.               break; 
  95.             // 正在充電事件 
  96.             case CommonEventSupport.COMMON_EVENT_CHARGING: 
  97.               LogUtils.info(TAG,"action:"+action); 
  98.               break; 
  99.           } 
  100.  
  101.  
  102.           //以下為如果有耗時操作時,選擇執(zhí)行的代碼 
  103.           final AsyncCommonEventResult result = goAsyncCommonEvent(); 
  104.           Runnable runnable=new Runnable() { 
  105.            @Override 
  106.            public void run() { 
  107.              // 待執(zhí)行的操作,由開發(fā)者定義 
  108.              myEventHandle.sendEvent(100); 
  109.  
  110.  
  111.              result.finishCommonEvent(); // 調(diào)用finish結(jié)束異步操作 
  112.            } 
  113.          }; 
  114.          myEventHandle.postTask(runnable); 
  115.     } 
  116.   } 
  117.  
  118.    private class MyEventHandle extends EventHandler{ 
  119.  
  120.     public MyEventHandle(EventRunner runner) throws IllegalArgumentException { 
  121.       super(runner); 
  122.     } 
  123.  
  124.      @Override 
  125.      protected void processEvent(InnerEvent event) { 
  126.        super.processEvent(event); 
  127.        //處理事件,由開發(fā)者撰寫 
  128.        int evnetID=event.eventId; 
  129.        LogUtils.info(TAG,"evnetID:"+evnetID); 
  130.  
  131.      } 
  132.    } 
  133.  
  134.  
  135.   @Override 
  136.   protected void onStop() { 
  137.     super.onStop(); 
  138.     try { 
  139.       CommonEventManager.unsubscribeCommonEvent(subscriber); 
  140.       LogUtils.info(TAG, "unsubscribeCommonEvent success."); 
  141.     } catch (RemoteException e) { 
  142.       LogUtils.error(TAG, "Exception occurred during unsubscribeCommonEvent invocation."); 
  143.     } 
  144.   } 

2.LogUtils

  1. public class LogUtils { 
  2.     private static final String TAG_LOG = "LogUtil"
  3.  
  4.     private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, LogUtils.TAG_LOG); 
  5.  
  6.     private static final String LOG_FORMAT = "%{public}s: %{public}s"
  7.  
  8.     private LogUtils() { } 
  9.  
  10.     /** 
  11.      * Print debug log 
  12.      * 
  13.      * @param tag log tag 
  14.      * @param msg log message 
  15.      */ 
  16.     public static void debug(String tag, String msg) { 
  17.         HiLog.debug(LABEL_LOG, LOG_FORMAT, tag, msg); 
  18.     } 
  19.  
  20.     /** 
  21.      * Print info log 
  22.      * 
  23.      * @param tag log tag 
  24.      * @param msg log message 
  25.      */ 
  26.     public static void info(String tag, String msg) { 
  27.         HiLog.info(LABEL_LOG, LOG_FORMAT, tag, msg); 
  28.     } 
  29.  
  30.     /** 
  31.      * Print warn log 
  32.      * 
  33.      * @param tag log tag 
  34.      * @param msg log message 
  35.      */ 
  36.     public static void warn(String tag, String msg) { 
  37.         HiLog.warn(LABEL_LOG, LOG_FORMAT, tag, msg); 
  38.     } 
  39.  
  40.     /** 
  41.      * Print error log 
  42.      * 
  43.      * @param tag log tag 
  44.      * @param msg log message 
  45.      */ 
  46.     public static void error(String tag, String msg) { 
  47.         HiLog.error(LABEL_LOG, LOG_FORMAT, tag, msg); 
  48.     } 

3. xml 布局文件:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <DirectionalLayout 
  3.   xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.   ohos:height="match_parent" 
  5.   ohos:orientation="vertical" 
  6.   ohos:width="match_parent"
  7.  
  8.  
  9.   <DirectionalLayout 
  10.     ohos:height="match_content" 
  11.     ohos:width="match_parent" 
  12.     ohos:left_margin="20vp" 
  13.     ohos:right_margin="20vp" 
  14.     ohos:top_margin="50vp" 
  15.     ohos:orientation="vertical"
  16.     <Button 
  17.       ohos:id="$+id:btPublisher" 
  18.       ohos:height="match_content" 
  19.       ohos:width="match_content" 
  20.       ohos:text_size="22vp" 
  21.       ohos:text_color="#ffffff" 
  22.       ohos:text="發(fā)布無序公共事件" 
  23.       ohos:padding="20vp" 
  24.       ohos:background_element="#00ffff"/> 
  25.  
  26.     <Button 
  27.       ohos:id="$+id:btSubscriber" 
  28.       ohos:height="match_content" 
  29.       ohos:width="match_content" 
  30.       ohos:text_size="22vp" 
  31.       ohos:text_color="#ffffff" 
  32.       ohos:text="訂閱公共事件" 
  33.       ohos:padding="20vp" 
  34.       ohos:top_margin="30vp" 
  35.       ohos:background_element="#00ffff"/> 
  36.   </DirectionalLayout> 
  37.  
  38. </DirectionalLayout> 

 

想了解更多內(nèi)容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)

https://harmonyos.51cto.com

 

責(zé)任編輯:jianghua 來源: 鴻蒙社區(qū)
相關(guān)推薦

2013-10-11 12:59:04

StrixMesh突發(fā)事件

2021-09-23 10:00:57

鴻蒙HarmonyOS應(yīng)用

2021-08-26 09:50:06

鴻蒙HarmonyOS應(yīng)用

2021-08-31 14:58:52

鴻蒙HarmonyOS應(yīng)用

2021-09-03 15:27:17

鴻蒙HarmonyOS應(yīng)用

2021-01-18 10:59:27

大數(shù)據(jù)公共事件大數(shù)據(jù)+

2021-08-27 09:57:18

鴻蒙HarmonyOS應(yīng)用

2009-07-02 09:56:24

導(dǎo)入事件驅(qū)動技術(shù)JSP Servlet

2022-04-27 18:06:12

數(shù)字安全數(shù)據(jù)安全網(wǎng)絡(luò)安全

2023-04-17 16:14:55

靜態(tài)訂閱鴻蒙

2017-08-13 18:17:46

網(wǎng)絡(luò)文學(xué)賦能IP

2011-08-08 07:46:39

政務(wù)

2020-05-07 17:56:48

物聯(lián)網(wǎng)人工智能技術(shù)

2020-05-07 21:49:53

物聯(lián)網(wǎng)智慧AI

2018-09-18 11:47:17

2019-04-23 14:25:40

區(qū)塊鏈數(shù)字貨幣比特幣
點贊
收藏

51CTO技術(shù)棧公眾號