The system provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. You can subscribe to the CES to listen for common system events such as screen-off and screen-on. In addition, you can use COMMON_EVENT_BOOT_COMPLETED to listen for the power-on event.
The code snippet is as follows:
import { commonEventManager } from '@kit.BasicServicesKit';
let subscriber:commonEventManager.CommonEventSubscriber;
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
events: ['usual.event.SCREEN_OFF'], // Subscribe to screen out public events
priority:80
}
commonEventManager.createSubscriber(subscribeInfo, (err, data) => {
if (err) {
console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
return;
}
console.info('Succeeded in creating subscriber1.');
subscriber = data;
// Subscribe to public event callbacks
commonEventManager.subscribe(subscriber, (err, data) => {
if (err) {
console.error(`Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`);
return;
} else {
console.info(`Succeeded in subscribe common event Succeeded1 `);
}
})
}) Reference