在开发过程中我我们可能需要接收一些通知,例如网络的改变,蓝牙的连接,短信接收等等。有助于我们为用户提供更好的体验。
首先我们需要创建通知的订阅者,需要继承CommonEventSubscriber类并实现其抽象方法。
public class MyCommonEventSubscriber extends CommonEventSubscriber {
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "MyCommonEventSubscriber");
public MyCommonEventSubscriber(CommonEventSubscribeInfo subscribeInfo) {
super(subscribeInfo);
}
@Override
public void onReceiveEvent(CommonEventData commonEventData) {
// 当应用程序收到新的公共事件时回调
Intent intent = commonEventData.getIntent();
// 判断动作类型
switch (intent.getAction()){
case CommonEventSupport.COMMON_EVENT_CONFIGURATION_CHANGED:
HiLog.info(LABEL_LOG,"屏幕旋转");
break;
case CommonEventSupport.COMMON_EVENT_SCREEN_ON:
HiLog.info(LABEL_LOG,"亮屏");
break;
default:
break;
}
}
}
然后需要在Ability中设置我们需要订阅哪些通知。
MatchingSkills matchingSkills = new MatchingSkills();
matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON); // 亮屏事件
matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_CONFIGURATION_CHANGED); // 屏幕旋转事件
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
MyCommonEventSubscriber subscriber = new MyCommonEventSubscriber(subscribeInfo);
try {
CommonEventManager.subscribeCommonEvent(subscriber);
} catch (RemoteException e) {
e.printStackTrace();
}
启动对应的Ability就可以接收通知了。具体支持哪些通知我们可以看看CommonEventSupport类?
?
|