add sample for DistributedCommonEvent

Signed-off-by: caopan <caopan8@huawei.com>
This commit is contained in:
caopan 2021-07-06 21:36:34 +08:00
parent 3a9e553ba9
commit 1af1715ebe
16 changed files with 573 additions and 0 deletions

View File

@ -0,0 +1,5 @@
分布式通知及事件
===============
分布式通知及事件功能框架,提供封装发布公共事件信息的方法、设置发布者的过滤条件、提供在订户收到新的公共事件时将被回调的方法、提供订阅,取消订阅和发布公共事件的方法。
本示例展示了如何跨设备订阅和退订公共事件操作。

View File

@ -0,0 +1,34 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'com.huawei.ohos.app'
ohos {
compileSdkVersion 5
defaultConfig {
compatibleSdkVersion 4
}
}
buildscript {
repositories {
maven {
url 'https://repo.huaweicloud.com/repository/maven/'
}
maven {
url 'https://developer.huawei.com/repo/'
}
jcenter()
}
dependencies {
classpath 'com.huawei.ohos:hap:2.4.4.2'
}
}
allprojects {
repositories {
maven {
url 'https://repo.huaweicloud.com/repository/maven/'
}
maven {
url 'https://developer.huawei.com/repo/'
}
jcenter()
}
}

View File

@ -0,0 +1,19 @@
apply plugin: 'com.huawei.ohos.hap'
ohos {
compileSdkVersion 5
defaultConfig {
compatibleSdkVersion 4
}
buildTypes {
release {
proguardOpt {
proguardEnabled false
rulesFiles 'proguard-rules.pro'
}
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
}

View File

@ -0,0 +1,53 @@
{
"app": {
"bundleName": "ohos.samples.distributedcommoneventsample",
"version": {
"code": 1000000,
"name": "1.0"
}
},
"deviceConfig": {},
"module": {
"package": "ohos.samples.distributedcommoneventsample",
"name": ".MainAbility",
"reqCapabilities": [
"video_support"
],
"deviceType": [
"default"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "entry",
"moduleType": "entry",
"installationFree":false
},
"abilities": [
{
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"orientation": "portrait",
"formsEnabled": false,
"name": ".MainAbility",
"icon": "$media:icon",
"description": "$string:mainability_description",
"label": "$string:app_name",
"type": "page",
"launchType": "standard"
}
],
"reqPermissions": [
{
"name": "ohos.permission.GET_DISTRIBUTED_DEVICE_INFO"
}
]
}
}

View File

@ -0,0 +1,157 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.samples.distributedcommoneventsample;
import ohos.samples.distributedcommoneventsample.utils.LogUtil;
import ohos.aafwk.content.Intent;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.event.commonevent.MatchingSkills;
import ohos.rpc.RemoteException;
import java.util.List;
/**
* Plugin class
*/
public class DistributeNotificationPlugin {
private static final String TAG = "DistributeNotificationPlugin";
private static final String TEST_ACTION = "usual.event.test2";
private static final String NOTIFICATION_KEY = "notification_key";
private static final String NOTIFICATION_CONTENT = "Receive CommonEvent Success";
private CommonEventSubscriber commonEventSubscriber;
private DistributeNotificationEventListener eventListener;
/**
* publish CommonEvent
*/
public void publishCommonEvent() {
LogUtil.info(TAG, "publish CommonEvent begin");
Intent intent = new Intent();
intent.setAction(TEST_ACTION);
intent.setParam(NOTIFICATION_KEY, NOTIFICATION_CONTENT);
CommonEventData eventData = new CommonEventData(intent);
try {
CommonEventManager.publishCommonEvent(eventData);
LogUtil.info("publishCommonEvent", "the action of Intent is:" + TEST_ACTION);
if (eventListener != null) {
eventListener.onEventPublish("CommonEvent Publish Success");
}
} catch (RemoteException e) {
LogUtil.error(TAG, "CommonEvent publish Error!");
}
}
/**
* CommonEvent Subscribe
*/
public void subscribeCommonEvent() {
LogUtil.info(TAG, "CommonEvent onSubscribe begin.");
MatchingSkills skills = new MatchingSkills();
skills.addEvent(TEST_ACTION);
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(skills);
List<DeviceInfo> deviceInfos = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ALL_DEVICE);
if (deviceInfos.size() == 0) {
LogUtil.error(TAG, "No online devices found");
subscribeInfo.setDeviceId("");
} else {
subscribeInfo.setDeviceId(deviceInfos.get(0).getDeviceId());
LogUtil.info(TAG, "onSubscribe subscribeInfo setDeviceId:" + deviceInfos.get(0).getDeviceId());
}
commonEventSubscriber = new CommonEventSubscriber(subscribeInfo) {
@Override
public void onReceiveEvent(CommonEventData commonEventData) {
LogUtil.info(TAG, "CommonEventData onReceiveEvent begin");
if (commonEventData == null) {
LogUtil.info(TAG, "commonEventData is null.");
return;
}
Intent intent = commonEventData.getIntent();
if (intent == null) {
LogUtil.debug(TAG, "commonEventData getIntent is null.");
return;
}
String receivedAction = intent.getAction();
LogUtil.info(TAG, "onReceiveEvent action:" + receivedAction);
if (receivedAction.equals(TEST_ACTION)) {
String notificationContent = intent.getStringParam(NOTIFICATION_KEY);
if (eventListener != null) {
eventListener.onEventReceive(notificationContent);
}
}
}
};
LogUtil.info(TAG, "CommonEventManager subscribeCommonEvent begin.");
try {
CommonEventManager.subscribeCommonEvent(commonEventSubscriber);
if (eventListener != null) {
eventListener.onEventSubscribe("CommonEvent Subscribe Success");
}
} catch (RemoteException exception) {
LogUtil.error(TAG, "CommonEvent Subscribe Error!");
}
}
/**
* CommonEvent Unsubscribe
*/
public void unsubscribeCommonEvent() {
LogUtil.info(TAG, "CommonEvent onUnsubscribe begin.");
if (commonEventSubscriber == null) {
LogUtil.info(TAG, "CommonEvent onUnsubscribe commonEventSubscriber is null");
return;
}
try {
CommonEventManager.unsubscribeCommonEvent(commonEventSubscriber);
if (eventListener != null) {
eventListener.onEventUnsubscribe("CommonEvent Unsubscribe Success");
}
} catch (RemoteException exception) {
LogUtil.error(TAG, "unsubscribeCommonEvent remoteException!");
}
commonEventSubscriber = null;
}
/**
* interface
*
*/
public interface DistributeNotificationEventListener {
void onEventPublish(String result);
void onEventSubscribe(String result);
void onEventUnsubscribe(String result);
void onEventReceive(String result);
}
public void setEventListener(DistributeNotificationEventListener eventListener) {
this.eventListener = eventListener;
}
}

View File

@ -0,0 +1,32 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.samples.distributedcommoneventsample;
import ohos.samples.distributedcommoneventsample.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
/**
* MainAbility
*/
public class MainAbility extends Ability {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setMainRoute(MainAbilitySlice.class.getName());
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.samples.distributedcommoneventsample.slice;
import ohos.samples.distributedcommoneventsample.DistributeNotificationPlugin;
import ohos.samples.distributedcommoneventsample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.window.dialog.ToastDialog;
/**
* MainAbilitySlice
*/
public class MainAbilitySlice extends AbilitySlice
implements DistributeNotificationPlugin.DistributeNotificationEventListener {
private static final int TOAST_DURATION = 3000;
private DistributeNotificationPlugin notificationPlugin;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_main_ability_slice);
notificationPlugin = new DistributeNotificationPlugin();
notificationPlugin.setEventListener(this);
initComponents();
}
private void initComponents() {
Component publishButton = findComponentById(ResourceTable.Id_publish);
publishButton.setClickedListener(component -> notificationPlugin.publishCommonEvent());
Component subscribeButton = findComponentById(ResourceTable.Id_subscribe);
subscribeButton.setClickedListener(component -> notificationPlugin.subscribeCommonEvent());
Component unsubscribeButton = findComponentById(ResourceTable.Id_unsubscribe);
unsubscribeButton.setClickedListener(component -> notificationPlugin.unsubscribeCommonEvent());
}
@Override
public void onEventPublish(String result) {
showToast(result);
}
@Override
public void onEventSubscribe(String result) {
showToast(result);
}
@Override
public void onEventUnsubscribe(String result) {
showToast(result);
}
@Override
public void onEventReceive(String result) {
showToast(result);
}
@Override
public void onStop() {
super.onStop();
notificationPlugin = null;
}
private void showToast(String msg) {
ToastDialog dialog = new ToastDialog(this);
dialog.setDuration(TOAST_DURATION);
dialog.setAutoClosable(false);
dialog.setContentText(msg);
dialog.show();
}
}

View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.samples.distributedcommoneventsample.utils;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import java.util.Locale;
/**
* Log utils
*/
public class LogUtil {
private static final String TAG_LOG = "DistributedCommonEventSample";
private static final int DOMAIN_ID = 0xD000F00;
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, DOMAIN_ID, LogUtil.TAG_LOG);
private static final String LOG_FORMAT = "%s: %s";
private LogUtil() {
/* Do nothing */
}
/**
* Print debug log
*
* @param tag log tag
* @param msg log message
*/
public static void debug(String tag, String msg) {
HiLog.debug(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, tag, msg));
}
/**
* Print info log
*
* @param tag log tag
* @param msg log message
*/
public static void info(String tag, String msg) {
HiLog.info(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, tag, msg));
}
/**
* Print warn log
*
* @param tag log tag
* @param msg log message
*/
public static void warn(String tag, String msg) {
HiLog.warn(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, tag, msg));
}
/**
* Print error log
*
* @param tag log tag
* @param msg log message
*/
public static void error(String tag, String msg) {
HiLog.error(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, tag, msg));
}
}

View File

@ -0,0 +1,12 @@
{
"string": [
{
"name": "app_name",
"value": "DistributedCommonEvent"
},
{
"name": "mainability_description",
"value": "hap sample empty page"
}
]
}

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (c) 2021 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<corners
ohos:radius="60"/>
<solid
ohos:color="#1976D2"/>
<stroke
ohos:color="#ff00ff7f"
ohos:width="0.4vp"/>
</shape>

View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (c) 2021 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:height="match_parent"
ohos:alignment="horizontal_center|vertical_center"
ohos:orientation="vertical">
<Text
ohos:width="match_parent"
ohos:height="match_content"
ohos:top_margin="10vp"
ohos:text_alignment="center"
ohos:text="Click the button to send CommonEvent"
ohos:text_size="15fp"/>
<Button
ohos:id="$+id:publish"
ohos:width="180vp"
ohos:height="35vp"
ohos:text="Publish"
ohos:text_color="#ffffff"
ohos:top_margin="10vp"
ohos:text_size="15fp"
ohos:background_element="$graphic:button_bg"/>
<Text
ohos:width="match_parent"
ohos:height="match_content"
ohos:top_margin="10vp"
ohos:text_alignment="center"
ohos:text="Click the button to subscribe for the CommonEvent"
ohos:text_size="15fp"/>
<Button
ohos:id="$+id:subscribe"
ohos:width="180vp"
ohos:height="35vp"
ohos:text_color="#ffffff"
ohos:text="Subscribe"
ohos:top_margin="10vp"
ohos:text_size="15fp"
ohos:background_element="$graphic:button_bg"/>
<Text
ohos:width="match_parent"
ohos:height="match_content"
ohos:top_margin="10vp"
ohos:text_alignment="center"
ohos:text="Click the button to unsubscribe for the CommonEvent"
ohos:text_size="15fp"/>
<Button
ohos:id="$+id:unsubscribe"
ohos:width="180vp"
ohos:height="35vp"
ohos:text_color="#ffffff"
ohos:text="Unsubscribe"
ohos:top_margin="10vp"
ohos:text_size="15fp"
ohos:background_element="$graphic:button_bg"/>
</DirectionalLayout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

View File

@ -0,0 +1 @@
include ':entry'