source
stringlengths
14
113
code
stringlengths
10
21.3k
application-dev\device\driver\externaldevice-guidelines.md
private async queryTargetDeviceId(): Promise<number> { try { const devices: Array<deviceManager.Device> = deviceManager.queryDevices(deviceManager.BusType.USB); const index = devices.findIndex((item: deviceManager.Device) => { let usbDevice = item as deviceManager.USBDevice; // If the product ID and vendor ID of the peripheral are unknown, you can view the information about the connected USB device in the log. hilog.info(0, 'testTag', `usbDevice.productId = ${usbDevice.productId}, usbDevice.vendorId = ${usbDevice.vendorId}`); return usbDevice.productId === productId && usbDevice.vendorId === vendorId; }); if (index < 0) { hilog.error(0, 'testTag', 'can not find device'); return -1; } return devices[index].deviceId; } catch (error) { hilog.error(0, 'testTag', `queryDevice failed, err: ${JSON.stringify(error)}`); } return -1; }
application-dev\device\driver\externaldevice-guidelines.md
private async getDriverRemote(deviceId: number): Promise<rpc.IRemoteObject | null> { try { let remoteDeviceDriver: deviceManager.RemoteDeviceDriver = await deviceManager.bindDriverWithDeviceId(deviceId, (err: BusinessError, id: number) => { hilog.info(0, 'testTag', `device[${id}] id disconnect, err: ${JSON.stringify(err)}}`); }); return remoteDeviceDriver.remote; } catch (error) { hilog.error(0, 'testTag', `bindDriverWithDeviceId failed, err: ${JSON.stringify(error)}`); } return null; }
application-dev\device\driver\externaldevice-guidelines.md
private async communicateWithRemote(): Promise<void> { const deviceId: number = await this.queryTargetDeviceId(); if (deviceId < 0) { hilog.error(0, 'testTag', 'can not find target device'); return; } this.remote = await this.getDriverRemote(deviceId); if (this.remote === null) { hilog.error(0, 'testTag', `getDriverRemote failed`); return; } let option = new rpc.MessageOption(); let data = new rpc.MessageSequence(); let reply = new rpc.MessageSequence(); // Send "Hello" to the driver. data.writeString(this.message); try { await this.remote.sendMessageRequest(REQUEST_CODE, data, reply, option); // Obtain the "Hello world" information returned by the driver. this.message = reply.readString(); hilog.info(0, 'testTag', `sendMessageRequest, message: ${this.message}}`); } catch (error) { hilog.error(0, 'testTag', `sendMessageRequest failed, err: ${JSON.stringify(error)}`); } }
application-dev\device\driver\externaldevice-guidelines.md
build() { Row() { Column() { Text (this.message) // "Hello" is displayed. .fontSize(60) .fontWeight(FontWeight.Bold) .onClick (() => { // Click Hello to communicate with the remote driver object. The message "Hello World" is displayed. this.communicateWithRemote(); }) } .width('100%') } .height('100%') }
application-dev\device\driver\externaldevice-guidelines.md
import { deviceManager } from '@kit.DriverDevelopmentKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\device\driver\externaldevice-guidelines.md
try { // For example, deviceId is 12345678. You can use queryDevices() to obtain the deviceId. let deviceInfos : Array<deviceManager.DeviceInfo> = deviceManager.queryDeviceInfo(12345678); for (let item of deviceInfos) { console.info(`Device id is ${item.deviceId}`) } } catch (error) { let err: BusinessError = error as BusinessError; console.error(`Failed to query device info. Code is ${err.code}, message is ${err.message}`); }
application-dev\device\driver\externaldevice-guidelines.md
try { // In this example, driver-12345 is the driver UID. During application development, you can use queryDeviceInfo to query the driver UID and use it as the input parameter. let driverInfos : Array<deviceManager.DriverInfo> = deviceManager.queryDriverInfo("driver-12345"); for (let item of driverInfos) { console.info(`driver name is ${item.driverName}`) } } catch (error) { let err: BusinessError = error as BusinessError; console.error(`Failed to query driver info. Code is ${err.code}, message is ${err.message}`); }
application-dev\device\location\fenceExtensionAbility.md
import { FenceExtensionAbility, geoLocationManager } from '@kit.LocationKit'; import { notificationManager } from '@kit.NotificationKit'; import { Want, wantAgent } from '@kit.AbilityKit'; export class MyFenceExtensionAbility extends FenceExtensionAbility { onFenceStatusChange(transition: geoLocationManager.GeofenceTransition, additions: Record<string, string>): void { // Receive the geofence status change event and process the service logic. console.info(`on geofence transition,id:${transition.geofenceId},event:${transition.transitionEvent},additions:${JSON.stringify(additions)}`); // Send a geofence notification. let wantAgentInfo: wantAgent.WantAgentInfo = { wants: [ { bundleName: 'com.example.myapplication', abilityName: 'EntryAbility', parameters: { "geofenceId": transition?.geofenceId, "transitionEvent": transition?.transitionEvent, } } as Want ], actionType: wantAgent.OperationType.START_ABILITY, requestCode: 100 }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentMy) => { let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: `Geofence Notification`, text: `on geofence transition,id:${transition.geofenceId},event:${transition.transitionEvent},additions:${JSON.stringify(additions)}`, } }, notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION, wantAgent: wantAgentMy }; notificationManager.publish(notificationRequest); }); } }
application-dev\device\location\geocode-guidelines.md
import { geoLocationManager } from '@kit.LocationKit';
application-dev\device\location\geocode-guidelines.md
import { geoLocationManager } from '@kit.LocationKit'; try { let isAvailable = geoLocationManager.isGeocoderAvailable(); } catch (err) { console.error("errCode:" + JSON.stringify(err)); }
application-dev\device\location\geocode-guidelines.md
let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; try { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { console.error('getAddressesFromLocation err: ' + JSON.stringify(err)); } else { console.info('getAddressesFromLocation data: ' + JSON.stringify(data)); } }); } catch (err) { console.error("errCode:" + JSON.stringify(err)); }
application-dev\device\location\geocode-guidelines.md
let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; try { geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { console.error('getAddressesFromLocationName err: ' + JSON.stringify(err)); } else { console.info('getAddressesFromLocationName data: ' + JSON.stringify(data)); } }); } catch (err) { console.error("errCode:" + JSON.stringify(err)); }
application-dev\device\location\geofence-guidelines.md
import { geoLocationManager } from '@kit.LocationKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { notificationManager } from '@kit.NotificationKit';
application-dev\device\location\geofence-guidelines.md
// Set the action type through operationType of WantAgentInfo. let geofence: geoLocationManager.Geofence = { "latitude": 34.12, "longitude": 124.11, "radius": 10000.0, "expiration": 10000.0 }
application-dev\device\location\geofence-guidelines.md
let transitionStatusList: Array<geoLocationManager.GeofenceTransitionEvent> = [ geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_ENTER, geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_EXIT, ];
application-dev\device\location\geofence-guidelines.md
// GEOFENCE_TRANSITION_EVENT_ENTER event let notificationRequest1: notificationManager.NotificationRequest = { id: 1, content: { notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "Geofence Notification", text: "Geofence Entry", additionalText: "" } } }; // Create a notification object for GEOFENCE_TRANSITION_EVENT_EXIT. let notificationRequest2: notificationManager.NotificationRequest = { id: 2, content: { notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "Geofence Notification", text: 'Geofence Exit', additionalText: "" } } };
application-dev\device\location\geofence-guidelines.md
// Save the created notification objects to Array in the same sequence as in transitionStatusList. let notificationRequestList: Array<notificationManager.NotificationRequest> = [notificationRequest1, notificationRequest2]; // Construct a gnssGeofenceRequest object. let gnssGeofenceRequest: geoLocationManager.GnssGeofenceRequest = { // Geofence attributes, including the circle center and radius. geofence: geofence, // Specify the types of geofence transition events to listen for. monitorTransitionEvents: transitionStatusList, // Specify the notification objects for geofence transition events. This parameter is optional. notifications: notificationRequestList, // Specify the callback used to receive geofence transition events. geofenceTransitionCallback: (err : BusinessError, transition : geoLocationManager.GeofenceTransition) => { if (err) { console.error('geofenceTransitionCallback: err=' + JSON.stringify(err)); } if (transition) { console.info("GeofenceTransition: %{public}s", JSON.stringify(transition)); } } } try { // Add a geofence. geoLocationManager.addGnssGeofence(gnssGeofenceRequest).then((id) => { // Obtain the geofence ID after the geofence is successfully added. console.info("addGnssGeofence success, fence id: " + id); let fenceId = id; }).catch((err: BusinessError) => { console.error("addGnssGeofence failed, promise errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message); }); } catch(error) { console.error("addGnssGeofence failed, err:" + JSON.stringify(error)); }
application-dev\device\location\geofence-guidelines.md
// fenceId is obtained after geoLocationManager.addGnssGeofence is successfully executed. let fenceId = 1; try { geoLocationManager.removeGnssGeofence(fenceId).then(() => { console.info("removeGnssGeofence success fenceId:" + fenceId); }).catch((error : BusinessError) => { console.error("removeGnssGeofence: error=" + JSON.stringify(error)); }); } catch(error) { console.error("removeGnssGeofence: error=" + JSON.stringify(error)); }
application-dev\device\location\location-guidelines.md
import { geoLocationManager } from '@kit.LocationKit';
application-dev\device\location\location-guidelines.md
import { geoLocationManager } from '@kit.LocationKit'; try { let locationEnabled = geoLocationManager.isLocationEnabled(); } catch (err) { console.error("errCode:" + err.code + ", message:" + err.message); }
application-dev\device\location\location-guidelines.md
import { geoLocationManager } from '@kit.LocationKit'; import { BusinessError } from '@kit.BasicServicesKit' try { let location = geoLocationManager.getLastLocation(); } catch (err) { console.error("errCode:" + JSON.stringify(err)); }
application-dev\device\location\location-guidelines.md
import { geoLocationManager } from '@kit.LocationKit'; import { BusinessError } from '@kit.BasicServicesKit' let request: geoLocationManager.SingleLocationRequest = { 'locatingPriority': geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED, 'locatingTimeoutMs': 10000 } try { geoLocationManager.getCurrentLocation(request).then((result) => { // Call getCurrentLocation to obtain the current device location by using a promise. console.info('current location: ' + JSON.stringify(result)); }) .catch((error:BusinessError) => { // Receive the reported error code. console.error('promise, getCurrentLocation: error=' + JSON.stringify(error)); }); } catch (err) { console.error("errCode:" + JSON.stringify(err)); }
application-dev\device\location\location-guidelines.md
import { geoLocationManager } from '@kit.LocationKit'; let request: geoLocationManager.ContinuousLocationRequest= { 'interval': 1, 'locationScenario': geoLocationManager.UserActivityScenario.NAVIGATION } let locationCallback = (location:geoLocationManager.Location):void => { console.info('locationCallback: data: ' + JSON.stringify(location)); }; try { geoLocationManager.on('locationChange', request, locationCallback); } catch (err) { console.error("errCode:" + JSON.stringify(err)); }
application-dev\device\location\location-guidelines.md
// The callback must be the same as that passed by the **on** API. geoLocationManager.off('locationChange', locationCallback);
application-dev\device\sensor\sensor-guidelines-as.md
import { sensor } from '@kit.SensorServiceKit';
application-dev\device\sensor\sensor-guidelines-as.md
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); }, { interval: 'game' });
application-dev\device\sensor\sensor-guidelines-as.md
sensor.off(sensor.SensorId.ACCELEROMETER);
application-dev\device\sensor\sensor-guidelines.md
import { sensor } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\device\sensor\sensor-guidelines.md
sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => { if (error) { console.info('getSensorList failed'); } else { console.info('getSensorList success'); for (let i = 0; i < data.length; i++) { console.info(JSON.stringify(data[i])); } } });
application-dev\device\sensor\sensor-guidelines.md
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); }, { interval: 100000000 });
application-dev\device\sensor\sensor-guidelines.md
sensor.once(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); });
application-dev\device\sensor\sensor-guidelines.md
sensor.off(sensor.SensorId.ACCELEROMETER);
application-dev\device\sensor\vibrator-guidelines-as.md
import { vibrator } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { // Start vibration. vibrator.startVibration({ type: 'time', duration: 1000, }, { id: 0, usage: 'alarm' }, (error: BusinessError) => { if (error) { console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); return; } console.info('Succeed in starting vibration'); }); } catch (err) { let e: BusinessError = err as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); }
application-dev\device\sensor\vibrator-guidelines-as.md
import { vibrator } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { // Stop vibration in all modes. vibrator.stopVibration((error: BusinessError) => { if (error) { console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); return; } console.info('Succeed in stopping vibration'); }) } catch (error) { let e: BusinessError = error as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); }
application-dev\device\sensor\vibrator-guidelines.md
import { vibrator } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { // Start vibration. vibrator.startVibration({ type: 'time', duration: 1000, }, { id: 0, usage: 'alarm' }, (error: BusinessError) => { if (error) { console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); return; } console.info('Succeed in starting vibration'); }); } catch (err) { let e: BusinessError = err as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); }
application-dev\device\sensor\vibrator-guidelines.md
import { vibrator } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { // Check whether 'haptic.effect.soft' is supported. vibrator.isSupportEffect('haptic.effect.soft', (err: BusinessError, state: boolean) => { if (err) { console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); return; } console.info('Succeed in querying effect'); if (state) { try { // Start vibration. vibrator.startVibration({ type: 'preset', effectId: 'haptic.effect.soft', count: 1, intensity: 50, }, { usage: 'unknown' }, (error: BusinessError) => { if (error) { console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); } else { console.info('Succeed in starting vibration'); } }); } catch (error) { let e: BusinessError = error as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); } } }) } catch (error) { let e: BusinessError = error as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); }
application-dev\device\sensor\vibrator-guidelines.md
import { vibrator } from '@kit.SensorServiceKit'; import { resourceManager } from '@kit.LocalizationKit'; import { BusinessError } from '@kit.BasicServicesKit'; const fileName: string = 'xxx.json'; @Entry @Component struct Index { uiContext = this.getUIContext(); build() { Row() { Column() { Button('alarm-file') .onClick(() => { // Obtain the file descriptor of the vibration configuration file. let rawFd: resourceManager.RawFileDescriptor | undefined = this.uiContext.getHostContext()?.resourceManager.getRawFdSync(fileName); if (rawFd != undefined) { // Start vibration. try { vibrator.startVibration({ type: "file", hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length } }, { id: 0, usage: 'alarm' // The switch control is subject to the selected type. }, (error: BusinessError) => { if (error) { console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); return; } console.info('Succeed in starting vibration'); }); } catch (err) { let e: BusinessError = err as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); } } // Close the file descriptor of the vibration configuration file. this.uiContext.getHostContext()?.resourceManager.closeRawFdSync(fileName); }) } .width('100%') } .height('100%') } }
application-dev\device\sensor\vibrator-guidelines.md
import { vibrator } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => { if (error) { console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); return; } console.info('Succeed in stopping vibration'); }) } catch (err) { let e: BusinessError = err as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); }
application-dev\device\sensor\vibrator-guidelines.md
import { vibrator } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { // Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, (error: BusinessError) => { if (error) { console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); return; } console.info('Succeed in stopping vibration'); }) } catch (err) { let e: BusinessError = err as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); }
application-dev\device\sensor\vibrator-guidelines.md
import { vibrator } from '@kit.SensorServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { // Stop vibration in all modes. vibrator.stopVibration((error: BusinessError) => { if (error) { console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); return; } console.info('Succeed in stopping vibration'); }) } catch (error) { let e: BusinessError = error as BusinessError; console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`); }
application-dev\device\stationary\deviceStatus-guidelines.md
import { deviceStatus } from '@kit.MultimodalAwarenessKit';
application-dev\device\stationary\deviceStatus-guidelines.md
try { deviceStatus.on('steadyStandingDetect', (data:deviceStatus.SteadyStandingStatus) => { console.info('now status = ' + data); }); } catch (err) { console.info('on failed, err = ' + err); }
application-dev\device\stationary\deviceStatus-guidelines.md
try { deviceStatus.off('steadyStandingDetect'); } catch (err) { console.info('off failed, err = ' + err); }
application-dev\device\stationary\deviceStatus-guidelines.md
import { Callback } from '@ohos.base'; // Define the callback variable. let callback : Callback<deviceStatus.SteadyStandingStatus> = (data : deviceStatus.SteadyStandingStatus) => { console.info('now status = ' + data); }; // Subscribe to a specific callback of steady standing state change events. try { deviceStatus.on('steadyStandingDetect', callback); } catch (err) { console.info('on failed, err = ' + err); } // Unsubscribe from the specific callback of steady standing state change events. try { deviceStatus.off('steadyStandingDetect', callback); } catch (err) { console.info('off failed, err = ' + err); }
application-dev\device\stationary\motion-guidelines.md
import { motion } from '@kit.MultimodalAwarenessKit'; import { BusinessError } from '@kit.BasicServicesKit';
application-dev\device\stationary\stationary-guidelines.md
algoPara_.resultantAcc = sqrt((algoPara_.x * algoPara_.x) + (algoPara_.y * algoPara_.y) + (algoPara_.z * algoPara_.z)); if ((algoPara_.resultantAcc > RESULTANT_ACC_LOW_THRHD) && (algoPara_.resultantAcc < RESULTANT_ACC_UP_THRHD)) { if (state_ == STILL) { return; } counter_--; if (counter_ == 0) { counter_ = COUNTER_THRESHOLD; UpdateStateAndReport(VALUE_ENTER, STILL, TYPE_ABSOLUTE_STILL); } } else { counter_ = COUNTER_THRESHOLD; if (state_ == UNSTILL) { return; } UpdateStateAndReport(VALUE_EXIT, UNSTILL, TYPE_ABSOLUTE_STILL); }
application-dev\device\stationary\stationary-guidelines.md
import { stationary } from '@kit.MultimodalAwarenessKit'; import { BusinessError } from '@kit.BasicServicesKit'; let reportLatencyNs = 1000000000; try { stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { console.log('data='+ JSON.stringify(data)); }) } catch (error) { let message = (error as BusinessError).message; console.error('stationary on failed:' + message); }
application-dev\device\stationary\stationary-guidelines.md
import { stationary } from '@kit.MultimodalAwarenessKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { stationary.once('still', (data) => { console.log('data='+ JSON.stringify(data)); }) } catch (error) { let message = (error as BusinessError).message; console.error('stationary once failed:' + message); }
application-dev\device\stationary\stationary-guidelines.md
import { stationary } from '@kit.MultimodalAwarenessKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { stationary.off('still', stationary.ActivityEvent.ENTER, (data) => { console.log('data='+ JSON.stringify(data)); }) } catch (error) { let message = (error as BusinessError).message; console.error('stationary off failed:' + message); }
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { usageStatistics } from '@kit.BackgroundTasksKit'
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryBundleEvents(0, 20000000000000).then( (res : Array<usageStatistics.BundleEvents>) => { console.log('BUNDLE_ACTIVE queryBundleEvents promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleEvents promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleEvents promise result ' + JSON.stringify(res[i])); } }).catch((err : BusinessError)=> { console.error('BUNDLE_ACTIVE queryBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.queryBundleEvents(0, 20000000000000, (err : BusinessError, res : Array<usageStatistics.BundleEvents>) => { if (err) { console.log('BUNDLE_ACTIVE queryBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryBundleEvents callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleEvents callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleEvents callback result ' + JSON.stringify(res[i])); } } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryBundleStatsInfos(0, 20000000000000).then( (res : usageStatistics.BundleStatsMap) => { console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback result ' + JSON.stringify(res)); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE queryBundleStatsInfos promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.queryBundleStatsInfos(0, 20000000000000, (err : BusinessError, res : usageStatistics.BundleStatsMap) => { if (err) { console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback result ' + JSON.stringify(res)); } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryCurrentBundleEvents(0, 20000000000000).then( (res : Array<usageStatistics.BundleEvents>) => { console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise result ' + JSON.stringify(res[i])); } }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE queryCurrentBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.queryCurrentBundleEvents(0, 20000000000000, (err : BusinessError, res : Array<usageStatistics.BundleEvents>) => { if (err) { console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback result ' + JSON.stringify(res[i])); } } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000).then( (res : Array<usageStatistics.BundleStatsInfo>) => { console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise result ' + JSON.stringify(res[i])); } }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000, (err : BusinessError, res : Array<usageStatistics.BundleStatsInfo>) => { if (err) { console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback result ' + JSON.stringify(res[i])); } } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryAppGroup().then( (res : number) => { console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Callback mode usageStatistics.queryAppGroup((err : BusinessError, res : number) => { if(err) { console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res)); } }); // Synchronous mode let priorityGroup = usageStatistics.queryAppGroupSync();
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.isIdleState("com.ohos.camera").then( (res : boolean) => { console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE isIdleState promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.isIdleState("com.ohos.camera", (err : BusinessError, res : boolean) => { if (err) { console.log('BUNDLE_ACTIVE isIdleState callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res)); } }); // Synchronous mode let isIdleState = usageStatistics.isIdleStateSync("com.ohos.camera");
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryModuleUsageRecords(1000).then( (res : Array<usageStatistics.HapModuleInfo>) => { console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise succeeded'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise result ' + JSON.stringify(res[i])); } }).catch( (err : BusinessError)=> { console.error('BUNDLE_ACTIVE queryModuleUsageRecords promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Promise mode when maxNum is not specified usageStatistics.queryModuleUsageRecords().then( (res : Array<usageStatistics.HapModuleInfo>) => { console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise succeeded'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise result ' + JSON.stringify(res[i])); } }).catch( (err : BusinessError)=> { console.error('BUNDLE_ACTIVE queryModuleUsageRecords promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.queryModuleUsageRecords(1000, (err : BusinessError, res : Array<usageStatistics.HapModuleInfo>) => { if(err) { console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback succeeded.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback result ' + JSON.stringify(res[i])); } } }); // Asynchronous callback mode when maxNum is not specified usageStatistics.queryModuleUsageRecords((err : BusinessError, res : Array<usageStatistics.HapModuleInfo>) => { if(err) { console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback succeeded.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback result ' + JSON.stringify(res[i])); } } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryNotificationEventStats(0, 20000000000000).then( (res : Array<usageStatistics.DeviceEventStats>) => { console.log('BUNDLE_ACTIVE queryNotificationEventStats promise success.'); console.log('BUNDLE_ACTIVE queryNotificationEventStats promise result ' + JSON.stringify(res)); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE queryNotificationEventStats promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.queryNotificationEventStats(0, 20000000000000, (err : BusinessError, res : Array<usageStatistics.DeviceEventStats>) => { if(err) { console.log('BUNDLE_ACTIVE queryNotificationEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryNotificationEventStats callback success.'); console.log('BUNDLE_ACTIVE queryNotificationEventStats callback result ' + JSON.stringify(res)); } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.queryDeviceEventStats(0, 20000000000000).then( (res : Array<usageStatistics.DeviceEventStats>) => { console.log('BUNDLE_ACTIVE queryDeviceEventStates promise success.'); console.log('BUNDLE_ACTIVE queryDeviceEventStates promise result ' + JSON.stringify(res)); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE queryDeviceEventStats promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode usageStatistics.queryDeviceEventStats(0, 20000000000000, (err : BusinessError, res : Array<usageStatistics.DeviceEventStats>) => { if(err) { console.log('BUNDLE_ACTIVE queryDeviceEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryDeviceEventStats callback success.'); console.log('BUNDLE_ACTIVE queryDeviceEventStats callback result ' + JSON.stringify(res)); } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode when bundleName is specified let bundleName = "com.ohos.camera"; usageStatistics.queryAppGroup(bundleName).then( (res : number) => { console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode when bundleName is specified let bundleName = "com.ohos.camera"; usageStatistics.queryAppGroup(bundleName, (err : BusinessError, res : number) => { if(err) { console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res)); } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode let bundleName = "com.example.deviceUsageStatistics"; let newGroup = usageStatistics.GroupType.DAILY_GROUP; usageStatistics.setAppGroup(bundleName, newGroup).then( () => { console.log('BUNDLE_ACTIVE setAppGroup promise succeeded.'); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE setAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode let bundleName = "com.example.deviceUsageStatistics"; let newGroup = usageStatistics.GroupType.DAILY_GROUP; usageStatistics.setAppGroup(bundleName, newGroup, (err : BusinessError) => { if(err) { console.log('BUNDLE_ACTIVE setAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE setAppGroup callback succeeded.'); } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode function onBundleGroupChanged (res : usageStatistics.AppGroupCallbackInfo) { console.log('BUNDLE_ACTIVE registerAppGroupCallBack RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appOldGroup is : ' + res.appOldGroup); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appNewGroup is : ' + res.appNewGroup); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result changeReason is : ' + res.changeReason); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result userId is : ' + res.userId); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName); }; usageStatistics.registerAppGroupCallBack(onBundleGroupChanged).then( () => { console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise succeeded.'); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE registerAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Asynchronous callback mode function onBundleGroupChanged (res : usageStatistics.AppGroupCallbackInfo) { console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appOldGroup is : ' + res.appOldGroup); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appNewGroup is : ' + res.appNewGroup); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result changeReason is : ' + res.changeReason); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result userId is : ' + res.userId); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName); }; usageStatistics.registerAppGroupCallBack(onBundleGroupChanged, (err : BusinessError) => { if(err) { console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback success.'); } });
application-dev\device-usage-statistics\device-usage-statistics-use-guide.md
import { BusinessError } from '@kit.BasicServicesKit'; // Promise mode usageStatistics.unregisterAppGroupCallBack().then( () => { console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack promise succeeded.'); }).catch( (err : BusinessError) => { console.error('BUNDLE_ACTIVE unregisterAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message); }); // Callback mode usageStatistics.unregisterAppGroupCallBack((err : BusinessError) => { if(err) { console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message); } else { console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback success.'); } });
application-dev\dfx\appfreeze-guidelines.md
private getForeachKey(item: xxx): string { //... return `${item.xxx2}${item.xxx2}...${item.themeStyle}`; }
application-dev\dfx\appfreeze-guidelines.md
+ if (!CheckEmptyUtils.isEmpty(themeStyleInfo.iconResourcePath) && + themeStyleInfo.iconResourcePath !== this.themeStyle.iconResourcePath) { + this.isStyleChanged = true; + this.themeStyle.iconResourcePath = themeStyleInfo.iconResourcePath; --> themeStyle is associated with iconResourcePath. + }
application-dev\dfx\appfreeze-guidelines.md
public static xxxFunction(fileUris: string[]): void { //... for (const fileuril of fileUrils) { let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY); //... } //... }
application-dev\dfx\appfreeze-guidelines.md
public static xxxFunction(fileUris: string[]): void { //... for (const fileuril of fileUrils) { let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY); //... } //... }
application-dev\dfx\appfreeze-guidelines.md
public static async xxxFunction(fileUris: string[]): void { //... AppStorage.setOrCreate<boolean>('isLoadingPic', true); --> This function is used to display the page load effect. for (const fileuril of fileUrils) { let file = await fs.open(fileUri, fs.OpenMode.READ_ONLY); //... } //... }
application-dev\dfx\apprecovery-guidelines.md
import { AbilityStage, appRecovery } from '@kit.AbilityKit'; export default class MyAbilityStage extends AbilityStage { onCreate() { console.info("[Demo] MyAbilityStage onCreate"); appRecovery.enableAppRecovery(appRecovery.RestartFlag.ALWAYS_RESTART, appRecovery.SaveOccasionFlag.SAVE_WHEN_ERROR | appRecovery.SaveOccasionFlag.SAVE_WHEN_BACKGROUND, appRecovery.SaveModeFlag.SAVE_WITH_FILE); } }
application-dev\dfx\apprecovery-guidelines.md
import { AbilityConstant, appRecovery, errorManager } from '@kit.AbilityKit';
application-dev\dfx\apprecovery-guidelines.md
import { appRecovery, errorManager, UIAbility } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; let registerId = -1; let callback: errorManager.ErrorObserver = { onUnhandledException(errMsg) { console.log(errMsg); appRecovery.saveAppState(); appRecovery.restartApp(); } } export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability console.log("[Demo] EntryAbility onWindowStageCreate"); registerId = errorManager.on('error', callback); windowStage.loadContent("pages/index", (err, data) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); }) } }
application-dev\dfx\apprecovery-guidelines.md
import { AbilityConstant, UIAbility } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onSaveState(state:AbilityConstant.StateType, wantParams: Record<string, Object>) { // Ability has called to save app data console.log("[Demo] EntryAbility onSaveState"); wantParams["myData"] = "my1234567"; return AbilityConstant.OnSaveResult.ALL_AGREE; } }
application-dev\dfx\apprecovery-guidelines.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; let abilityWant: Want; export default class EntryAbility extends UIAbility { storage: LocalStorage | undefined = undefined; onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("[Demo] EntryAbility onCreate"); abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { this.storage = new LocalStorage(); if (want.parameters) { let recoveryData = want.parameters["myData"]; this.storage.setOrCreate("myData", recoveryData); this.context.restoreWindowStage(this.storage); } } } }
application-dev\dfx\apprecovery-guidelines.md
import { errorManager, UIAbility } from '@kit.AbilityKit'; let registerId = -1; export default class EntryAbility extends UIAbility { onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.log("[Demo] EntryAbility onWindowStageDestroy"); errorManager.off('error', registerId, (err) => { console.error("[Demo] err:", err); }); } }
application-dev\dfx\apprecovery-guidelines.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; let abilityWant: Want; export default class EntryAbility extends UIAbility { storage: LocalStorage | undefined = undefined onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("[Demo] EntryAbility onCreate"); abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { this.storage = new LocalStorage(); if (want.parameters) { let recoveryData = want.parameters["myData"]; this.storage.setOrCreate("myData", recoveryData); this.context.restoreWindowStage(this.storage); } } } onSaveState(state:AbilityConstant.StateType, wantParams: Record<string, Object>) { // Ability has called to save app data console.log("[Demo] EntryAbility onSaveState"); wantParams["myData"] = "my1234567"; return AbilityConstant.OnSaveResult.ALL_AGREE; } }
application-dev\dfx\apprecovery-guidelines.md
import { AbilityConstant, UIAbility, Want, wantConstant } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { if (want.parameters === undefined) { return; } if (want.parameters[wantConstant.Params.ABILITY_RECOVERY_RESTART] != undefined && want.parameters[wantConstant.Params.ABILITY_RECOVERY_RESTART] == true) { console.log("This ability need to recovery"); } } }
application-dev\dfx\errormanager-guidelines.md
import { AbilityConstant, errorManager, UIAbility, Want } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; import process from '@ohos.process'; let registerId = -1; let callback: errorManager.ErrorObserver = { onUnhandledException: (errMsg) => { console.info(errMsg); }, onException: (errorObj) => { console.info('onException, name: ', errorObj.name); console.info('onException, message: ', errorObj.message); if (typeof(errorObj.stack) === 'string') { console.info('onException, stack: ', errorObj.stack); } //After the callback is executed, exit the process synchronously to avoid triggering exceptions for multiple times. let pro = new process.ProcessManager(); pro.exit(0); } } let abilityWant: Want; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.info("[Demo] EntryAbility onCreate"); registerId = errorManager.on("error", callback); abilityWant = want; } onDestroy() { console.info("[Demo] EntryAbility onDestroy"); errorManager.off("error", registerId, (result) => { console.info("[Demo] result " + result.code + ";" + result.message); }); } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability console.info("[Demo] EntryAbility onWindowStageCreate"); windowStage.loadContent("pages/index", (err, data) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); }); } onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.info("[Demo] EntryAbility onWindowStageDestroy"); } onForeground() { // Ability has brought to foreground console.info("[Demo] EntryAbility onForeground"); } onBackground() { // Ability has back to background console.info("[Demo] EntryAbility onBackground"); } };
application-dev\dfx\errormanager-guidelines.md
import { AbilityConstant, errorManager, UIAbility, Want } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; import process from '@ohos.process'; function errorFunc(observer: errorManager.GlobalError) { console.info("[Demo] result name :" + observer.name); console.info("[Demo] result message :" + observer.message); console.info("[Demo] result stack :" + observer.stack); console.info("[Demo] result instanceName :" + observer.instanceName); console.info("[Demo] result instaceType :" + observer.instanceType); //After the callback is executed, exit the process synchronously to avoid triggering exceptions for multiple times. let pro = new process.ProcessManager(); pro.exit(0); } let abilityWant: Want; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.info("[Demo] EntryAbility onCreate"); errorManager.on("globalErrorOccurred", errorFunc); abilityWant = want; } onDestroy() { console.info("[Demo] EntryAbility onDestroy"); errorManager.off("globalErrorOccurred", errorFunc); } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability console.info("[Demo] EntryAbility onWindowStageCreate"); windowStage.loadContent("pages/index", (err, data) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); }); } onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.info("[Demo] EntryAbility onWindowStageDestroy"); } onForeground() { // Ability has brought to foreground console.info("[Demo] EntryAbility onForeground"); } onBackground() { // Ability has back to background console.info("[Demo] EntryAbility onBackground"); } };
application-dev\dfx\errormanager-guidelines.md
import { AbilityConstant, errorManager, UIAbility, Want } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; import process from '@ohos.process'; function promiseFunc(observer: errorManager.GlobalError) { console.info("[Demo] result name :" + observer.name); console.info("[Demo] result message :" + observer.message); console.info("[Demo] result stack :" + observer.stack); console.info("[Demo] result instanceName :" + observer.instanceName); console.info("[Demo] result instaceType :" + observer.instanceType); //After the callback is executed, exit the process synchronously to avoid triggering exceptions for multiple times. let pro = new process.ProcessManager(); pro.exit(0); } let abilityWant: Want; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.info("[Demo] EntryAbility onCreate"); errorManager.on("globalUnhandledRejectionDetected", promiseFunc); abilityWant = want; } onDestroy() { console.info("[Demo] EntryAbility onDestroy"); errorManager.off("globalUnhandledRejectionDetected", promiseFunc); } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability console.info("[Demo] EntryAbility onWindowStageCreate"); windowStage.loadContent("pages/index", (err, data) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); }); } onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.info("[Demo] EntryAbility onWindowStageDestroy"); } onForeground() { // Ability has brought to foreground console.info("[Demo] EntryAbility onForeground"); } onBackground() { // Ability has back to background console.info("[Demo] EntryAbility onBackground"); } };
application-dev\dfx\errormanager-guidelines.md
import { AbilityConstant, errorManager, UIAbility, Want } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; import process from '@ohos.process'; // Define freezeCallback function freezeCallback() { console.info("freezecallback"); } let abilityWant: Want; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.info("[Demo] EntryAbility onCreate"); errorManager.on("freeze", freezeCallback); abilityWant = want; } onDestroy() { console.info("[Demo] EntryAbility onDestroy"); errorManager.off("freeze", freezeCallback); } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability console.info("[Demo] EntryAbility onWindowStageCreate"); windowStage.loadContent("pages/index", (err, data) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); }); } onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.info("[Demo] EntryAbility onWindowStageDestroy"); } onForeground() { // Ability has brought to foreground console.info("[Demo] EntryAbility onForeground"); } onBackground() { // Ability has back to background console.info("[Demo] EntryAbility onBackground"); } };
application-dev\dfx\hiappevent-event-reporting.md
import { BusinessError } from '@kit.BasicServicesKit'; import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; @Entry @Component struct Index { @State message: string = 'Hello World' processorId: number = -1 build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Button("addProcessorTest").onClick(()=>{ // In Onclick(), add a data processor. let eventConfig: hiAppEvent.AppEventReportConfig = { domain: 'button', name: 'click', isRealTime: true }; let processor: hiAppEvent.Processor = { name: 'analytics_demo', debugMode: true, routeInfo: 'CN', onStartReport: true, onBackgroundReport: true, periodReport: 10, batchReport: 5, userIds: ['testUserIdName'], userProperties: ['testUserPropertyName'], eventConfigs: [eventConfig] }; this.processorId = hiAppEvent.addProcessor(processor); }) } .width('100%') } .height('100%') } }
application-dev\dfx\hiappevent-event-reporting.md
Button("userIdTest").onClick(()=>{ // Set the user ID in onClick(). hiAppEvent.setUserId('testUserIdName', '123456'); // Obtain the user ID set in onClick(). let userId = hiAppEvent.getUserId('testUserIdName'); hilog.info(0x0000, 'testTag', `userId: ${userId}`) })
application-dev\dfx\hiappevent-event-reporting.md
Button("userPropertyTest").onClick(()=>{ // Set the user property in onClick(). hiAppEvent.setUserProperty('testUserPropertyName', '123456'); // Obtain the user property in onClick(). let userProperty = hiAppEvent.getUserProperty('testUserPropertyName'); hilog.info(0x0000, 'testTag', `userProperty: ${userProperty}`) })
application-dev\dfx\hiappevent-event-reporting.md
Button("writeTest").onClick(()=>{ // In onClick(), use hiAppEvent.write() to log an event when the button is clicked. let eventParams: Record<string, number> = { 'click_time': 100 }; let eventInfo: hiAppEvent.AppEventInfo = { // Define the event domain. domain: "button", // Define the event name. name: "click", // Define the event type. eventType: hiAppEvent.EventType.BEHAVIOR, // Define the event parameters. params: eventParams, }; hiAppEvent.write(eventInfo).then(() => { hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) }); })
application-dev\dfx\hiappevent-event-reporting.md
Button("removeProcessorTest").onClick(()=>{ // In Onclick(), add removeProcessor(). hiAppEvent.removeProcessor(this.processorId); })
application-dev\dfx\hiappevent-watcher-address-sanitizer-events-arkts.md
import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit';
application-dev\dfx\hiappevent-watcher-address-sanitizer-events-arkts.md
hiAppEvent.addWatcher({ // Set the watcher name. The system identifies different watchers based on their names. name: "watcher", // Add the system events to watch, for example, the address sanitizer event. appEventFilters: [ { domain: hiAppEvent.domain.OS, names: [hiAppEvent.event.ADDRESS_SANITIZER] } ], // Implement a callback for the registered system event so that you can apply custom processing to the event data obtained. onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => { hilog.info(0x0000, 'testTag', `HiAppEvent onReceive: domain=${domain}`); for (const eventGroup of appEventGroups) { // The event name uniquely identifies a system event. hilog.info(0x0000, 'testTag', `HiAppEvent eventName=${eventGroup.name}`); for (const eventInfo of eventGroup.appEventInfos) { // Customize how to process the event data obtained, for example, print the event data in the log. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.domain=${eventInfo.domain}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.name=${eventInfo.name}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.eventType=${eventInfo.eventType}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.time=${eventInfo.params['time']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.bundle_version=${eventInfo.params['bundle_version']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.bundle_name=${eventInfo.params['bundle_name']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.pid=${eventInfo.params['pid']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.uid=${eventInfo.params['uid']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.type=${eventInfo.params['type']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.external_log=${JSON.stringify(eventInfo.params['external_log'])}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.log_over_limit=${eventInfo.params['log_over_limit']}`); } } } });
application-dev\dfx\hiappevent-watcher-address-sanitizer-events-arkts.md
export const test: () => void;
application-dev\dfx\hiappevent-watcher-address-sanitizer-events-arkts.md
import testNapi from 'libentry.so' @Entry @Component struct Index { build() { Row() { Column() { Button("address-sanitizer").onClick(() => { testNapi.test(); }) } .width('100%') } .height('100%') } }
application-dev\dfx\hiappevent-watcher-address-sanitizer-events-ndk.md
import testNapi from 'libentry.so' @Entry @Component struct Index { build() { Row() { Column() { Button("address-sanitizer").onClick(() => { testNapi.test(); }) } .width('100%') } .height('100%') } }
application-dev\dfx\hiappevent-watcher-app-events-arkts.md
import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit';
application-dev\dfx\hiappevent-watcher-app-events-arkts.md
hiAppEvent.addWatcher({ // Set the watcher name. The system identifies different watchers based on their names. name: "watcher1", // Add the application events to watch, for example, button onclick events. appEventFilters: [{ domain: "button" }], // Set the subscription callback trigger condition. For example, trigger a callback when one event is logged. triggerCondition: { row: 1 }, // Implement the subscription callback function to apply custom processing to the obtained event logging data. onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => { // If the holder object is null, return after the error is recorded. if (holder == null) { hilog.error(0x0000, 'testTag', "HiAppEvent holder is null"); return; } hilog.info(0x0000, 'testTag', `HiAppEvent onTrigger: curRow=%{public}d, curSize=%{public}d`, curRow, curSize); let eventPkg: hiAppEvent.AppEventPackage | null = null; // Fetch the subscription event package based on the specified threshold (512 KB by default) until all subscription event data is fetched. // If all subscription event data is fetched, return a null event package to end this subscription callback. while ((eventPkg = holder.takeNext()) != null) { // Apply custom processing to the event logging data obtained, for example, print the event logging data in the log. hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId); hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row); hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size); for (const eventInfo of eventPkg.data) { hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo); } } } }); 3. In the **entry/src/main/ets/pages/Index.ets** file, import the dependent modules.
application-dev\dfx\hiappevent-watcher-app-events-arkts.md
Button("writeTest").onClick(()=>{ // In onClick(), use hiAppEvent.write() to log an event when the button is clicked. let eventParams: Record<string, number> = { 'click_time': 100 }; let eventInfo: hiAppEvent.AppEventInfo = { // Define the event domain. domain: "button", // Define the event name. name: "click", // Define the event type. eventType: hiAppEvent.EventType.BEHAVIOR, // Define the event parameters. params: eventParams, }; hiAppEvent.write(eventInfo).then(() => { hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) }); })
application-dev\dfx\hiappevent-watcher-crash-events-arkts.md
import { BusinessError } from '@kit.BasicServicesKit'; import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit';
application-dev\dfx\hiappevent-watcher-crash-events-arkts.md
// Assign a value to params, which is a key-value pair let params: Record<string, hiAppEvent.ParamType> = { "test_data": 100, }; // Set custom parameters for the crash event. hiAppEvent.setEventParam(params, hiAppEvent.domain.OS, hiAppEvent.event.APP_CRASH).then(() => { hilog.info(0x0000, 'testTag', `HiAppEvent success to set event param`); }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', `HiAppEvent code: ${err.code}, message: ${err.message}`); });
application-dev\dfx\hiappevent-watcher-crash-events-arkts.md
let watcher: hiAppEvent.Watcher = { // Set the watcher name. The system identifies different watchers based on their names. name: "watcher", // Add the system events to watch, for example, crash events. appEventFilters: [ { domain: hiAppEvent.domain.OS, names: [hiAppEvent.event.APP_CRASH] } ], // Implement a callback for the registered system event so that you can apply custom processing to the event data obtained. onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => { hilog.info(0x0000, 'testTag', `HiAppEvent onReceive: domain=${domain}`); for (const eventGroup of appEventGroups) { // The event name uniquely identifies a system event. hilog.info(0x0000, 'testTag', `HiAppEvent eventName=${eventGroup.name}`); for (const eventInfo of eventGroup.appEventInfos) { // Apply custom processing to the event data obtained, for example, print the event data in the log. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.domain=${eventInfo.domain}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.name=${eventInfo.name}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.eventType=${eventInfo.eventType}`); // Obtain the timestamp of the crash event. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.time=${eventInfo.params['time']}`); // Obtain the type of the crash event. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.crash_type=${eventInfo.params['crash_type']}`); // Obtain the foreground and background status of the crashed application. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.foreground=${eventInfo.params['foreground']}`); // Obtain the version information of the crashed application. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.bundle_version=${eventInfo.params['bundle_version']}`); // Obtain the bundle name of the crashed application. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.bundle_name=${eventInfo.params['bundle_name']}`); // Obtain the process ID of the crashed application. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.pid=${eventInfo.params['pid']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.uid=${eventInfo.params['uid']}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.uuid=${eventInfo.params['uuid']}`); // Obtain the exception type, cause, and call stack of the crash event. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.exception=${JSON.stringify(eventInfo.params['exception'])}`); // Obtain the log information about the crash event. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.hilog.size=${eventInfo.params['hilog'].length}`); // Obtain the error log file about the crash event. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.external_log=${JSON.stringify(eventInfo.params['external_log'])}`); hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.log_over_limit=${eventInfo.params['log_over_limit']}`); // Obtain the custom test_data of the crash event. hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.test_data=${eventInfo.params['test_data']}`); } } } }; hiAppEvent.addWatcher(watcher);
application-dev\dfx\hiappevent-watcher-crash-events-arkts.md
Button("appCrash").onClick(()=>{ // Construct a scenario in onClick() to trigger a crash event. let result: object = JSON.parse(""); })
application-dev\dfx\hiappevent-watcher-crash-events-arkts.md
// Remove the event watcher to unsubscribe from events. hiAppEvent.removeWatcher(watcher);
application-dev\dfx\hiappevent-watcher-freeze-events-arkts.md
import { BusinessError } from '@kit.BasicServicesKit'; import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit';
application-dev\dfx\hiappevent-watcher-freeze-events-arkts.md
// Assign a value to params, which is a key-value pair. let params: Record<string, hiAppEvent.ParamType> = { "test_data": 100, }; // Set custom parameters for the freeze event. hiAppEvent.setEventParam(params, hiAppEvent.domain.OS, hiAppEvent.event.APP_FREEZE).then(() => { hilog.info(0x0000, 'testTag', `HiAppEvent success to set svent param`); }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', `HiAppEvent code: ${err.code}, message: ${err.message}`); });