ILifecycle, ContextAccessibleAbility, AceAbility, AVBrowserService, FileAbility, FractionAbility, HostService, InputMethodAbility, IntentAbility, OffHostService, WorkSchedulerpublic class Ability extends AbilityContext implements ILifecycle
Note: In the description below, a Page, Service, or Data ability indicates an ability using the respective template, whereas the ability alone indicates an ability using any type of templates.
AbilitySlice. You must override
the onStart(ohos.aafwk.content.Intent) method and use the setMainRoute(java.lang.String) and
addActionRoute(java.lang.String,java.lang.String) methods to configure the entry of a Page ability.
Each application has a configuration file: config.json. This file is stored in the root directory of Java code.
├── entry │ ├── libs │ ├── src │ │ ├── main │ │ │ ├── java │ │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── myapplication │ │ │ │ ├── slice │ │ │ │ │ └── PageAbilitySlice.java │ │ │ │ └── PageAbility.java │ │ │ ├── resources │ │ │ │ ├── base │ │ │ │ │ ├── element │ │ │ │ │ │ └── string.json │ │ │ │ │ └── media │ │ │ │ │ └── icon.png │ │ │ │ └── rawfile │ │ │ └── config.json
Description of the file structure of an application is as follows:
entry stores the code, resource files, and configuration file of the application. The folder name is editable.
entry/libs stores third-party library files. This directory is automatically generated by the IDE upon project creation.
entry/src/main/java is used for code development. You can change file names in this directory as required. This directory is automatically generated by the IDE upon project creation.
entry/src/main/resources/base/media stores PNG and JPG image files for your application. This directory is automatically generated by the IDE upon project creation.
entry/src/main/resources/base/element stores resource files used for reading text resources. This directory is automatically generated by the IDE upon project creation.
The entry/src/main/config.json file is located in the main root directory. This file contains configuration information about the application. The system runs the application and displays contents on the UI based on the content of this file. This file is automatically generated by the IDE upon project creation.
To develop a new ability, you must register the ability in the config.json file. Example code:
{
"module":{
...
"abilities":[
{
...
"description": "Main ability of hiworld",
"name": ".MainAbility",
"label": "main ability",
"icon": "main-ability.png",
"type": "page",
"visible": true,
"orientation": "unspecified",
"launch-mode": "standard",
...
}
]
...
}
}
Note: All abilities of an application must be registered in this file and attached to the abilities
tag.
type tag indicates the type of templates used by an ability, and its value page,
service, or provider indicates the Page, Service, or Data template, respectively. The
type tag must be specified.name tag indicates the name of an ability and must be specified.As the fundamental unit of an application, an ability has the following four lifecycle states:
The figure below shows a complete ability lifecycle. A specific callback is executed for each state transition. You can override the callback methods.

Note: All Page abilities must implement onStart(ohos.aafwk.content.Intent) to set their UIs. To override a lifecycle
callback method, you must first call the callback method corresponding to the parent class, for example,
super.onStart(). The state transition is implemented on the main thread. Therefore, you are advised to
execute short logic in the lifecycle callback to prevent the main thread of the ability from being blocked.
The following are all lifecycle callback methods of the ability:
public class MainAbility extends Ability {
protected void onStart(Intent intent);
protected void onActive();
protected void onInactive();
protected void onForeground(Intent intent);
protected void onBackground();
protected void onStop();
}
For details on lifecycle callback, see AbilitySlice.
The startAbility(ohos.aafwk.content.Intent) method is used to start a new ability, which is placed at the top of the
ability stack. It uses the parameter Intent to describe the ability. The
code below shows how to start an ability:
Button button = new Button(this);
button.setClickedListener(listener -> {
Operation operation = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName("ohos.hiworld")
.withAbilityName("ohos.hiworld.MainAbility")
.build();
Intent intent = new Intent();
intent.setOperation(operation);
intent.setParam("age", 10);
startAbility(intent);
});
The connectAbility(ohos.aafwk.content.Intent,ohos.aafwk.ability.IAbilityConnection) method is used to connect to a Service ability. It has
two parameters: Intent and IAbilityConnection. Intent provides information about the target
Service ability to connect, and IAbilityConnection is a callback object used to notify you of the connection
result (success or failure).
In contrast to connectAbility(ohos.aafwk.content.Intent,ohos.aafwk.ability.IAbilityConnection), the
disconnectAbility(ohos.aafwk.ability.IAbilityConnection) method is used to disconnect from a connected Service ability.
For Service abilities, you can override the onConnect(ohos.aafwk.content.Intent) method to provide a RemoteObject for
calling. By default, null is returned.
protected IRemoteObject onConnect(Intent intent) {
return null;
}
SystemCapability.Aafwk#ABILITY| 限定符和类型 | 类 | 说明 |
|---|---|---|
static class |
Ability.LayoutParamsHelper |
Helps you use an
Intent to set the layout parameters of the application startup window. |
static class |
Ability.WindowAttributeHelper |
Helps you use an
Intent to set window attributes for the current application. |
| 限定符和类型 | 字段 | 说明 |
|---|---|---|
static int |
FORM_INVISIBLE |
Indicates the event that the form becomes invisible.
|
static int |
FORM_VISIBLE |
Indicates the event that the form becomes visible.
|
CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_RESOUCE_ONLY, CONTEXT_RESTRICTED, MODE_APPEND, MODE_PRIVATE| 构造器 | 说明 |
|---|---|
Ability() |
| 限定符和类型 | 方法 | 说明 |
|---|---|---|
void |
addActionRoute(String action,
String entry) |
Binds an action to
AbilitySlice. |
int |
batchInsert(Uri uri,
ValuesBucket[] values) |
Inserts multiple data records into the database.
|
PacMap |
call(String method,
String arg,
PacMap extras) |
Defines a method in this Data ability (implementation depending on child classes).
|
void |
cancelBackgroundRunning() |
Cancels background running of this ability to free up system memory.
|
boolean |
connectAbility(Intent intent,
IAbilityConnection conn) |
Connects an ability to a Service ability.
|
void |
continueAbility() |
Migrates this ability to another device on the same distributed network.
|
void |
continueAbility(String deviceId) |
Migrates this ability to the given device on the same distributed network.
|
void |
continueAbilityReversibly() |
Migrates this ability to another device on the same distributed network in a reversible way that allows this
ability to be migrated back to the local device through
reverseContinueAbility(). |
void |
continueAbilityReversibly(String deviceId) |
Migrates this ability to the given device on the same distributed network in a reversible way that allows this
ability to be migrated back to the local device through
reverseContinueAbility(). |
<T> FileDescriptor |
createPipeFile(Uri uri,
String mimeType,
PacMap pacMap,
T args,
PipeFileWriter<T> pipeFileWriter) |
Creates a data pipe, calls a background thread to write the data pointed to by the specified
Uri into
the pipe, and returns the FileDescriptor object used for data reading. |
int |
delete(Uri uri,
DataAbilityPredicates predicates) |
Deletes one or more data records.
|
Uri |
denormalizeUri(Uri uri) |
Converts the given normalized
uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. |
void |
disconnectAbility(IAbilityConnection conn) |
Disconnects an ability from a Service ability, in contrast to
connectAbility(ohos.aafwk.content.Intent,ohos.aafwk.ability.IAbilityConnection). |
void |
dispatchAccessibilityEventInfo(AccessibilityEventInfo info) |
Called when an accessibility event occurs on the component of this ability.
|
DataAbilityResult[] |
executeBatch(ArrayList<DataAbilityOperation> operations) |
Performs batch operations on the database.
|
void |
executeOperation(DataAbilityOperation operation,
DataAbilityResult[] refResults,
int refIndex) |
Executes an operation among the batch operations to be executed.
|
<T extends Component> |
findComponentById(int resId) |
Finds a component in the XML file based on the resource ID.
|
String |
getAbilityName() |
Obtains the class name in this ability name, without the prefixed bundle name.
|
AbilityPackage |
getAbilityPackage() |
Obtains the singleton
AbilityPackage object to which this ability belongs. |
boolean |
getAdmissionTransitionConcurEnabled() |
Generates an instance of animation parameters.
|
Transition |
getAdmissionTransitionObject() |
Gets the admission transition animation type.
|
Object |
getAVController() |
Obtains window media controller of an ability.
|
boolean |
getBackTransitionConcurEnabled() |
Generates an instance of animation parameters.
|
Transition |
getBackTransitionObject() |
Gets the back transition animation type.
|
IContinuationRegisterManager |
getContinuationRegisterManager() |
Obtains an
IContinuationRegisterManager object. |
ContinuationState |
getContinuationState() |
Obtains the migration state of this ability.
|
Component |
getCurrentFocus() |
Obtains the component that currently has window focus.
|
String[] |
getFileTypes(Uri uri,
String mimeTypeFilter) |
Obtains the MIME type of files.
|
Intent |
getIntent() |
Obtains the
Intent object that starts this ability. |
WindowManager.LayoutConfig |
getLayoutParams() |
Obtains window layout parameters of an ability.
|
Lifecycle |
getLifecycle() |
Obtains the
Lifecycle object of the current ability. |
String |
getOriginalDeviceId() |
Obtains the ID of the source device from which this ability is migrated.
|
Transition |
getQuitTransitionObject() |
Gets the quit transition animation type.
|
Transition |
getReadmissionTransitionObject() |
Gets the readmission transition animation type.
|
Transition |
getSharedItemAdmissionTransitionObject() |
Gets the SharedItem Admission transition animation type.
|
Transition |
getSharedItemBackTransitionObject() |
Gets the SharedItem Back transition animation type.
|
Transition |
getSharedItemQuitTransitionObject() |
Gets the SharedItem Quit transition animation type.
|
Transition |
getSharedItemReadmissionTransitionObject() |
Gets the sharedItem readmission transition animation type.
|
AbilityLifecycleExecutor.LifecycleState |
getState() |
Obtains the lifecycle state of this ability.
|
String |
getType(Uri uri) |
Obtains the MIME type matching the data specified by the URI of the Data ability.
|
int |
getVolumeTypeAdjustedByKey() |
Obtains the type of audio whose volume is adjusted by the volume button.
|
Window |
getWindow() |
Obtains the window corresponding to the current ability.
|
boolean |
hasWindowFocus() |
Checks whether the main window of this ability has window focus.
|
int |
insert(Uri uri,
ValuesBucket value) |
Inserts a data record into the database.
|
boolean |
isTemporary() |
Checks whether this ability is a temporary ability.
|
boolean |
isTerminating() |
Checks whether the current ability is being destroyed.
|
void |
keepBackgroundRunning(int id,
NotificationRequest notificationRequest) |
Keeps this Service ability in the background and displays a notification bar.
|
Uri |
normalizeUri(Uri uri) |
Converts the given
uri that refer to the Data ability into a normalized URI. |
protected void |
onAbilityResult(int requestCode,
int resultCode,
Intent resultData) |
Called when
startAbilityForResult(ohos.aafwk.content.Intent,int) is called to start an ability and the result is returned. |
protected FormState |
onAcquireFormState(Intent intent) |
Called to return a
FormState object. |
protected void |
onActive() |
Called back when an ability enters the ACTIVE state.
|
protected void |
onBackground() |
Called back when an ability enters the BACKGROUND state.
|
protected void |
onBackPressed() |
Called back when the Back key is pressed.
|
protected void |
onCastTempForm(long formId) |
Called when the form provider is notified that a temporary form is successfully converted to a normal form.
|
protected void |
onCommand(Intent intent,
boolean restart) |
已过时。
This change is effective since API version 3. Replaced by
onCommand(ohos.aafwk.content.Intent,boolean,int). |
protected void |
onCommand(Intent intent,
boolean restart,
int startId) |
Called back when Service is started.
|
void |
onConfigurationUpdated(Configuration configuration) |
Called when the system configuration is updated.
|
protected IRemoteObject |
onConnect(Intent intent) |
Called back when a Service ability is first connected to an ability.
|
protected AbilityForm |
onCreateForm() |
Called to return an
AbilityForm object. |
protected ProviderFormInfo |
onCreateForm(Intent intent) |
Called to return a
ProviderFormInfo object. |
protected void |
onDeleteForm(int formId) |
已过时。
This change is effective since API version 5. Replaced by
onDeleteForm(long). |
protected void |
onDeleteForm(long formId) |
Called to notify the form provider that a specified form has been deleted.
|
protected void |
onDisconnect(Intent intent) |
Called back when all abilities connected to a Service ability are disconnected.
|
void |
onEventDispatch() |
Called every time a key, touch, or trackball event is dispatched to this ability.
|
protected void |
onEventNotify(Map<Long,Integer> formEvents) |
Called when the form provider receives form events from the system.
|
protected void |
onForeground(Intent intent) |
Called back when the state of an ability changes from BACKGROUND to INACTIVE.
|
boolean |
onHotkeyTriggered(int keyCode,
KeyEvent keyEvent) |
Called when a hotkey is pressed.
|
protected void |
onInactive() |
Called back when an ability enters the INACTIVE state (an ability in this state is not interactive and may
change to the BACKGROUND or ACTIVE state).
|
protected void |
onInitialized(AbilityInfo abilityInfo) |
Called to carry
AbilityInfo to this ability after the ability is initialized. |
boolean |
onKeyDown(int keyCode,
KeyEvent keyEvent) |
Called when a key is pressed.
|
boolean |
onKeyPressAndHold(int keyCode,
KeyEvent keyEvent) |
Called when a key is pressed and held.
|
boolean |
onKeyUp(int keyCode,
KeyEvent keyEvent) |
Called when a key is released.
|
void |
onLeaveForeground() |
Called when this ability is about to leave the foreground and enter the background due to a user operation,
for example, when the user touches the Home key.
|
void |
onMemoryLevel(int level) |
Called when the system has determined to trim the memory, for example, when the ability is running in the
background and there is no enough memory for running as many background processes as possible.
|
void |
onMissionDeleted(Intent intent) |
Called when the user deletes the application that runs this Service ability from the mission list displayed
after the user touches and holds the Home key.
|
CharSequence |
onNewDescription() |
Called before this ability is background to generate a new description for this ability.
|
protected void |
onNewIntent(Intent intent) |
Called when the launch mode of an ability is set to singleton.
|
protected void |
onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) |
Called back when the display orientation of a screen changes.
|
protected void |
onPostActive() |
Called when the ability is completely activated after calling
onActive(). |
protected void |
onPostStart(PacMap pacMap) |
Called when the ability has been started by calling
onStart(ohos.aafwk.content.Intent) and onRestoreAbilityState(ohos.utils.PacMap). |
void |
onReconnect(Intent intent) |
Called when a new client attempts to connect to a Service ability after all previous client connections to it
are disconnected.
|
void |
onRequestPermissionsFromUserResult(int requestCode,
String[] permissions,
int[] grantResults) |
Called back after permissions are requested by using
AbilityContext.requestPermissionsFromUser(java.lang.String[],int). |
void |
onRestoreAbilityState(PacMap inState) |
Restores data and states of an ability when it is restored by the system.
|
void |
onSaveAbilityState(PacMap outState) |
Saves temporary data and states of this ability.
|
Uri |
onSetCaller() |
Called to set caller information for the application.
|
protected void |
onStart(Intent intent) |
Called back when an ability is started for initialization (it can be called only once in the entire lifecycle of
an ability).
|
protected void |
onStop() |
Called back before an ability is destroyed.
|
Object |
onStoreDataWhenConfigChange() |
Called to save the data to be destroyed when the system configuration is changed.
|
void |
onTopActiveAbilityChanged(boolean topActive) |
Called when this ability is moved to or removed from the top of the stack.
|
protected boolean |
onTouchEvent(TouchEvent event) |
Called when a touch event is dispatched to this ability.
|
protected void |
onTriggerFormEvent(int formId,
String message) |
已过时。
This change is effective since API version 5. Replaced by
onTriggerFormEvent(long,java.lang.String). |
protected void |
onTriggerFormEvent(long formId,
String message) |
Called when a specified message event defined by the form provider is triggered.
|
protected void |
onUnloadForm() |
Called when a form is released.
|
protected void |
onUpdateForm(int formId) |
已过时。
This change is effective since API version 5. Replaced by
onUpdateForm(long). |
protected void |
onUpdateForm(long formId) |
Called to notify the form provider to update a specified form.
|
void |
onWindowFocusChanged(boolean hasFocus) |
Called when this ability gains or loses window focus.
|
FileDescriptor |
openFile(Uri uri,
String mode) |
Opens a file.
|
RawFileDescriptor |
openRawFile(Uri uri,
String mode) |
Opens a raw file.
|
DataAbilityPredicates |
parsePredictionArgsReference(DataAbilityResult[] refResults,
DataAbilityOperation operation,
int numRef) |
Obtains the
DataAbilityPredicates object by parsing the database
operation results based on the specified operation. |
ValuesBucket |
parseValuesBucketReference(DataAbilityResult[] refResults,
DataAbilityOperation operation,
int numRefs) |
Obtains the
ValuesBucket object by parsing the database operation results
based on the specified operation. |
void |
postTask(Runnable task,
long delayTime) |
Posts a scheduled
Runnable task to a new non-UI thread. |
ResultSet |
query(Uri uri,
String[] columns,
DataAbilityPredicates predicates) |
Queries one or more data records in the database.
|
boolean |
reload(Uri uri,
PacMap extras) |
Reloads data in the database.
|
boolean |
reverseContinueAbility() |
Migrates this ability from another device on the same distributed network back to the local device.
|
void |
setAbilitySliceAnimator(AbilitySliceAnimator abilitySliceAnimator) |
Sets the transition animation among
AbilitySlice instances of the current ability. |
void |
setAdmissionTransitionConcurEnabled(boolean enabled) |
Gets the sharedItem admission transition animation type.
|
void |
setAdmissionTransitionObject(Transition transition) |
Sets the entrance transition animation type.
|
void |
setAVController(Object controller) |
Sets window media controller of an ability.The media controller containing media info of the window.
|
void |
setBackTransitionConcurEnabled(boolean enabled) |
Generates an instance of animation parameters.
|
void |
setBackTransitionObject(Transition transition) |
Sets the back transition animation type.
|
boolean |
setFormNextRefreshTime(long formId,
long nextTime) |
Sets the next dynamic refresh time of a form.
|
void |
setIntent(Intent intent) |
Sets the
Intent object that can be obtained by calling getIntent(). |
void |
setIsAmbientMode(boolean isEnabled) |
Sets whether to enable the Always on Display (AOD) mode for the window presented by this ability.
|
void |
setLayoutParams(WindowManager.LayoutConfig params) |
Sets window layout parameters of an ability.
|
void |
setMainRoute(String entry) |
Sets the main route of this ability.
|
void |
setQuitTransitionObject(Transition transition) |
Sets the quit transition animation type.
|
void |
setReadmissionTransitionObject(Transition transition) |
Sets the reentrance transition animation type.
|
void |
setResult(int resultCode,
Intent resultData) |
Sets the result code and data to be returned by this Page ability to the caller.
|
void |
setSharedItemAdmissionTransitionObject(Transition transition) |
Sets the sharedItem entrance transition animation type.
|
void |
setSharedItemBackTransitionObject(Transition transition) |
Sets the sharedItem back transition animation type.
|
void |
setSharedItemQuitTransitionObject(Transition transition) |
Sets the sharedItem quit transition animation type.
|
void |
setSharedItemReadmissionTransitionObject(Transition transition) |
Sets the sharedItem reentrance transition animation type.
|
boolean |
setSwipeToDismiss(boolean isEnabled) |
Sets whether a window and its ability finishes when swiped away.
|
void |
setUIContent(int layoutRes) |
Inflates layout resources by using the layout resource ID.
|
void |
setUIContent(ComponentContainer componentContainer) |
Inflates UI controls by using
ComponentContainer. |
void |
setVolumeTypeAdjustedByKey(int volumeType) |
Sets the type of audio whose volume will be adjusted by the volume button.
|
void |
setWindowBackgroundColor(int red,
int green,
int blue) |
Sets the background color of the window in RGB color mode.
|
void |
shutdown() |
Shuts down this Data ability.
|
void |
startAbility(Intent intent) |
Starts a new ability.
|
void |
startAbility(Intent intent,
IAbilityStartCallback callback) |
Starts a new ability.
|
void |
startAbility(Intent intent,
AbilityStartSetting abilityStartSetting) |
Starts a new ability with specific start settings.
|
void |
startAbility(Intent intent,
AbilityStartSetting abilityStartSetting,
AbilityTransitionUtils abilityTransitionUtils) |
Starts a new ability with specific start settings.
|
void |
startAbilityForResult(Intent intent,
int requestCode) |
Starts an ability and returns the execution result when the ability is destroyed.
|
void |
startAbilityForResult(Intent intent,
int requestCode,
AbilityStartSetting abilityStartSetting) |
Starts an ability with specific start settings and returns the execution result when the ability is destroyed.
|
void |
startAssistAbility(Intent intent,
IAssistanceChannel channel) |
Establishes a collaboration session with the specified ability.
|
boolean |
stopAbility(Intent intent) |
Destroys another Service ability.
|
int |
stopAssistAbility(AbilityAgent agent) |
Disconnects this collaboration session.
|
boolean |
supportHighPerformanceUI() |
Checks whether this ability supports high-performance UI rendering.
|
void |
terminateAbility() |
Destroys this Page or Service ability.
|
int |
update(Uri uri,
ValuesBucket value,
DataAbilityPredicates predicates) |
Updates one or more data records in the database.
|
boolean |
updateForm(int formId,
FormBindingData formBindingData) |
已过时。
This change is effective since API version 5. Replaced by
updateForm(long,ohos.aafwk.ability.FormBindingData). |
boolean |
updateForm(int formId,
ComponentProvider component) |
已过时。
This change is effective since API version 5. Replaced by
updateForm(long,ohos.agp.components.ComponentProvider). |
boolean |
updateForm(long formId,
FormBindingData formBindingData) |
Updates the content of a specified JS form.
|
boolean |
updateForm(long formId,
ComponentProvider component) |
Updates the content of a specified Java form.
|
attachBaseContext, canRequestPermission, compelVerifyCallerPermission, compelVerifyCallerUriPermission, compelVerifyPermission, compelVerifyPermission, compelVerifyUriPermission, compelVerifyUriPermission, compelVerifyUriPermission, createBundleContext, createParallelTaskDispatcher, createSerialTaskDispatcher, deleteFile, displayUnlockMissionMessage, getAbilityInfo, getAbilityManager, getAbilityPackageContext, getApplicationContext, getApplicationInfo, getAppType, getBundleCodePath, getBundleManager, getBundleName, getBundleResourcePath, getCacheDir, getCaller, getCallingAbility, getCallingBundle, getClassloader, getCodeCacheDir, getColor, getColorMode, getContext, getDatabaseDir, getDataDir, getDir, getDisplayOrientation, getDistributedDir, getElementName, getExternalCacheDir, getExternalCacheDirs, getExternalFilesDir, getExternalFilesDirs, getExternalMediaDirs, getFilesDir, getGlobalTaskDispatcher, getHapModuleInfo, getIntArray, getLastStoredDataWhenConfigChanged, getLocalClassName, getMainTaskDispatcher, getNoBackupFilesDir, getPattern, getPreferencesDir, getProcessInfo, getProcessName, getResourceManager, getResourceManager, getString, getString, getStringArray, getTheme, getThemeId, getUITaskDispatcher, init, isCredentialEncryptedStorage, isDeviceEncryptedStorage, isUpdatingConfigurations, lockMission, printDrawnCompleted, requestPermissionsFromUser, restart, setColorMode, setDisplayOrientation, setPattern, setShowOnLockScreen, setTheme, setTransitionAnimation, setWakeUpScreen, startAbilities, startAbility, startAbility, startAbility, switchToCredentialEncryptedStorageContext, switchToDeviceEncryptedStorageContext, terminateAbility, terminateAbilityResult, unlockMission, verifyCallingOrSelfPermission, verifyCallingPermission, verifyPermission, verifySelfPermissionpublic static final int FORM_INVISIBLE
onEventNotify(java.util.Map<java.lang.Long, java.lang.Integer>) callback is invoked.public static final int FORM_VISIBLE
onEventNotify(java.util.Map<java.lang.Long, java.lang.Integer>) callback is invoked.protected void onInitialized(AbilityInfo abilityInfo)
AbilityInfo to this ability after the ability is initialized.abilityInfo - Indicates the AbilityInfo object containing information about this ability.public void postTask(Runnable task, long delayTime) throws IllegalArgumentException
Runnable task to a new non-UI thread.
The task posted via this method will be executed in a new thread, which allows you to perform certain
time-consuming operations. To use this method, you must also override the supportHighPerformanceUI()
method. Additionally, the usage of this method must comply with the following constraints:
onActive() and onStop() of the ability slice must also be added to the parallel
thread.setUIContent(ohos.agp.components.ComponentContainer) to unlock the UI thread and wait until
the component tree is ready.task - Indicates the Runnable task to post.delayTime - Indicates the number of milliseconds after which the task will be executed.IllegalArgumentException - Throws this exception if the input parameter is invalid.public boolean supportHighPerformanceUI()
true if you want your ability to support high-performance UI rendering.true if this ability supports high-performance UI rendering; returns false
otherwise.public AbilityPackage getAbilityPackage()
AbilityPackage object to which this ability belongs.AbilityPackage object to which this ability belongs.public Window getWindow()
You can use a Window instance to control attributes of a window, such as
the window size, position, and padding.
public final void setUIContent(int layoutRes)
layoutRes - Indicates the layout resource ID, which cannot be a negative number.AbilitySliceRuntimeException - invalid argumentsetUIContent(ComponentContainer)public void setUIContent(ComponentContainer componentContainer)
ComponentContainer.
You can create a ComponentContainer instance that contains multiple components.
componentContainer - Indicates a set of customized components.AbilitySliceRuntimeException - invalid argumentsetUIContent(int)public void setAVController(Object controller)
controller - Indicates the object containing media info of the window. This parameter cannot be null.public Object getAVController()
null if no media controller
is set.public WindowManager.LayoutConfig getLayoutParams()
You can use layout parameters to control the window attributes of an ability, such as the position, length, and width.
null if no layout parameter is set.public void setLayoutParams(WindowManager.LayoutConfig params)
You can use layout parameters to control the window attributes of an ability, such as the position, length, and width.
params - Indicates the WindowManager.LayoutConfig object containing
the layout parameters. This parameter cannot be null.public <T extends Component> T findComponentById(int resId)
resId - Indicates the resource ID of the component.null otherwise.public void setIsAmbientMode(boolean isEnabled)
isEnabled - Specifies whether to enable the AOD mode. The value true means to enable it,
and false means the opposite.public IContinuationRegisterManager getContinuationRegisterManager()
IContinuationRegisterManager object.
You can use the IContinuationRegisterManager object to interact with
the hop task management service, including registering and unregistering the ability to migrate,
updating the device connection state, and showing the list of devices that can be selected for ability migration.
IContinuationRegisterManager object.public boolean onHotkeyTriggered(int keyCode,
KeyEvent keyEvent)
keyCode - Indicates the key code..keyEvent - Indicates the triggered key event.true if the key event is handled in this callback; returns false otherwise.public boolean onKeyDown(int keyCode,
KeyEvent keyEvent)
Ability gains focus, the key-down event for
the component will be handled first. This callback will not be invoked if the callback triggered for the key-down
event of the component returns true. The default implementation of this callback does nothing and returns
false.keyCode - Indicates the code of the key pressed.keyEvent - Indicates the key-down event.true if this event is handled and will not be passed further;
returns false if this event is not handled and should be passed to other handlers.onKeyUp(int, ohos.multimodalinput.event.KeyEvent)public boolean onKeyUp(int keyCode,
KeyEvent keyEvent)
Ability gains focus, the key-up event for
the component will be handled first. This callback will not be invoked if the callback triggered for the key-up
event of the component returns true. The default implementation of this callback does nothing and returns
false.keyCode - Indicates the code of the key released.keyEvent - Indicates the key-up event.true if this event is handled and will not be passed further;
returns false if this event is not handled and should be passed to other handlers.onKeyDown(int, ohos.multimodalinput.event.KeyEvent)public boolean onKeyPressAndHold(int keyCode,
KeyEvent keyEvent)
keyCode - Indicates the key code.keyEvent - Indicates the triggered key event.true if the key event is handled in this callback; returns false otherwise.protected void onBackPressed()
The default implementation destroys the ability. You can override this method.
public boolean connectAbility(Intent intent, IAbilityConnection conn)
This method can be called by a Page or Service ability, but the destination of the connection must be a
Service ability. You must implement the IAbilityConnection interface to obtain the proxy of the target
Service ability when the Service ability is connected.
The calling Context must have been started and have not been destroyed. Otherwise,
this method returns false. For example, when an AbilityForm supplier
calls this method in a callback triggered upon a component click or touch event, false may be returned
because the supplier may not be started.
connectAbility 在接口中 ContextconnectAbility 在类中 AbilityContextintent - Indicates the Service ability to connect.conn - Indicates the callback object when the Service ability is connected.true if the connection is successful; returns false otherwise.IllegalStateException - Throws this exception if the ability is not initialized.IllegalArgumentException - Throws this exception if the input parameter is null.Context.connectAbility(Intent, IAbilityConnection)public void disconnectAbility(IAbilityConnection conn)
connectAbility(ohos.aafwk.content.Intent,ohos.aafwk.ability.IAbilityConnection).disconnectAbility 在接口中 ContextdisconnectAbility 在类中 AbilityContextconn - Indicates the callback object when the Service ability is connected.IllegalStateException - Throws this exception if the ability is not initialized.IllegalArgumentException - Throws this exception if the input parameter is null.Context.disconnectAbility(IAbilityConnection)public final Lifecycle getLifecycle()
Lifecycle object of the current ability.getLifecycle 在接口中 ILifecycleLifecycle object.Lifecyclepublic int insert(Uri uri, ValuesBucket value)
uri - Indicates the position where the data is to insert.value - Indicates the data to insert.public int batchInsert(Uri uri, ValuesBucket[] values)
uri - Indicates the position where the data is to insert.values - Indicates the data to insert.public int delete(Uri uri, DataAbilityPredicates predicates)
uri - Indicates the database table storing the data to delete.predicates - Indicates filter criteria. If this parameter is null, all data records will be deleted by
default.public int update(Uri uri, ValuesBucket value, DataAbilityPredicates predicates)
uri - Indicates the database table storing the data to update.value - Indicates the data to update. This parameter can be null.predicates - Indicates filter criteria. If this parameter is null, all data records will be updated by
default.public ResultSet query(Uri uri, String[] columns, DataAbilityPredicates predicates)
uri - Indicates the database table storing the data to query.columns - Indicates the columns to be queried, in array, for example, {"name","age"}. You should define
the processing logic when this parameter is null.predicates - Indicates filter criteria. If this parameter is null, all data records will be queried by
default.public DataAbilityResult[] executeBatch(ArrayList<DataAbilityOperation> operations) throws OperationExecuteException
The batch operations to be executed on the database are encapsulated as DataAbilityOperation objects.
Each object corresponds to an operation, for example, inserting or deleting. The call result of each operation is
saved to and returned by the data array of the DataAbilityResult type.
operations - Indicates the data operation list, which can contain multiple operations on the database.OperationExecuteException - Throws this exception if the batch operation fails.public FileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException
uri - Indicates the path of the file to open.mode - Indicates the open mode, which can be "r" for read-only access, "w" for write-only access (erasing
whatever data is currently in the file), "wt" for write access that truncates any existing file,
"wa" for write-only access to append to any existing data, "rw" for read and write access on any
existing data, or "rwt" for read and write access that truncates any existing file.FileDescriptor object of the file descriptor.FileNotFoundException - Throws this exception if the file does not exist.public RawFileDescriptor openRawFile(Uri uri, String mode) throws FileNotFoundException
uri - Indicates the path of the raw file to open.mode - Indicates the open mode, which can be "r" for read-only access, "w" for write-only access (erasing
whatever data is currently in the file), "wt" for write access that truncates any existing file,
"wa" for write-only access to append to any existing data, "rw" for read and write access on any
existing data, or "rwt" for read and write access that truncates any existing file.RawFileDescriptor object containing file descriptor.FileNotFoundException - Throws this exception if the raw file does not exist.public <T> FileDescriptor createPipeFile(Uri uri, String mimeType, PacMap pacMap, T args, PipeFileWriter<T> pipeFileWriter) throws FileNotFoundException, IllegalStateException
Uri into
the pipe, and returns the FileDescriptor object used for data reading.
PipeFileWriter#write(FileDescriptor, Uri, String, PacMap, T)} must have been implemented
for writing data to a pipe. You should disable the FileDescriptor object returned by this method
after you finish using it.
uri - Indicates the source Uri object whose data will be written.mimeType - Indicates the MIME type of the data to write.pacMap - Indicates the PacMap object to be passed in this call. This parameter can be
null.args - Indicates the custom parameters that specify the data shared to the client. The type of
this parameter is the same as the generic type in PipeFileWriter}.pipeFileWriter - Indicates the instance of a class that implements
PipeFileWriter#write(FileDescriptor, Uri, String, PacMap, T)} for pipe data writing.FileDescriptor object for pipe data reading.IllegalStateException - Throws this exception if the data pipe fails to be created.FileNotFoundException - Throws this exception if the url not found.public String[] getFileTypes(Uri uri, String mimeTypeFilter)
uri - Indicates the path of the files to obtain.mimeTypeFilter - Indicates the MIME type of the files to obtain. This parameter cannot be set to
null.
1. "*/*": Obtains all types supported by a Data ability.
2. "image/*": Obtains files whose main type is image of any subtype.
3. "*/jpg": Obtains files whose subtype is JPG of any main type.
public PacMap call(String method, String arg, PacMap extras)
public void shutdown()
public String getType(Uri uri)
Data abilities supports general data types, including text, HTML, and JPEG.
uri - Indicates the URI of the data.uri.public boolean isTemporary()
true if this ability is temporary; returns false otherwise.protected void onStart(Intent intent)
Most initialization operations should be performed by calling this method. For example, you can use the
current method to call setMainRoute(java.lang.String) and
addActionRoute(java.lang.String,java.lang.String) to set the main router and action router for a Page ability.
intent - Indicates information carried when this ability is started. Note: For a Service ability,
null is passed.protected void onPostStart(PacMap pacMap)
onStart(ohos.aafwk.content.Intent) and onRestoreAbilityState(ohos.utils.PacMap).
Generally, this method is used for system classes to perform final initialization operations after an application starts. You do not need to implement this method for your application. When overriding this method, you must call the implementation of its parent class. Otherwise, an exception will be thrown.
pacMap - Indicates the data most recently provided in onSaveAbilityState(ohos.utils.PacMap).protected void onStop()
This method indicates the end of the ability lifecycle. It can be executed after the ability calls the
terminateAbility() method or the last ability slice of the ability calls the
AbilitySlice#terminate() method. Generally, this method is used to clear resources.
protected void onActive()
The ability in the ACTIVE state is in the foreground and is interactive.
protected void onUnloadForm()
protected void onPostActive()
onActive().
Generally, this method is used for system classes to perform final settings after an application is activated. You do not need to implement this method for your application. When overriding this method, you must call the implementation of its parent class. Otherwise, an exception will be thrown.
protected void onInactive()
INACTIVE is an intermediate state and does not last for a long period of time. Frequent switching between ACTIVE and INACTIVE is possible. Therefore, you can use this method to perform certain simple operations, for example, committing any changes.
protected void onForeground(Intent intent)
This is an intermediate state callback method. Generally, the system calls this method to refresh data status
and then calls back the onActive() method.
intent - Indicates information carried when the ability returns to the INACTIVE state.protected void onBackground()
A Page ability in the BACKGROUND state is invisible. You are advised to suspend threads related to the ability and clear some resources to free up system memory.
protected IRemoteObject onConnect(Intent intent)
This method is called only on Service abilities. You can override the method to return the proxy of a Service ability.
intent - Indicates connection information about the Service ability.protected void onDisconnect(Intent intent)
This method is called only on Service abilities. You can override the method to clear resources of the proxy of a Service ability.
intent - Indicates disconnection information about the Service ability.@Deprecated protected void onCommand(Intent intent, boolean restart)
onCommand(ohos.aafwk.content.Intent,boolean,int).This method can be called only by Service abilities. You can use the startAbility(ohos.aafwk.content.Intent) method to
start a Service ability. Then the system calls back the current method to use the transferred intent
parameter to execute its own logic.
intent - Indicates the intent of the Service ability to start.restart - Indicates the startup mode. The value true indicates that the Service ability is restarted
after being destroyed, and the value false indicates a normal startup.protected void onCommand(Intent intent, boolean restart, int startId)
This method can be called only by Service. You can use the startAbility(ohos.aafwk.content.Intent) method to start
Service. Then the system calls back the current method to use the transferred intent parameter to
execute its own logic.
intent - Indicates the intent of Service to start.restart - Indicates the startup mode. The value true indicates that Service is restarted after being
destroyed, and the value false indicates a normal startup.startId - Indicates the number of times the Service ability has been started. The startId is
incremented by 1 every time the ability is started. For example, if the ability has been started
for six times, the value of startId is 6.protected void onNewIntent(Intent intent)
intent - Indicates the new Intent containing information about the ability.public void onConfigurationUpdated(Configuration configuration)
configuration - Indicates the updated configuration information.protected boolean onTouchEvent(TouchEvent event)
false.event - Indicates information about the touch event.true if the event is handled; returns false otherwise.protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation)
You can override this method to implement your logic when the display orientation changes. By default, no operation is performed when the display orientation changes.
displayOrientation - Indicates the new display orientation. The following values are supported:
AbilityInfo.DisplayOrientation#LANDSCAPE, AbilityInfo.DisplayOrientation#PORTRAIT,
AbilityInfo.DisplayOrientation#FOLLOWRECENT, and AbilityInfo.DisplayOrientation#UNSPECIFIED.public void onMemoryLevel(int level)
level - Indicates the memory trim level, which shows the current memory usage status. The values and their
respective meanings are as follows:
5: The application is running properly and will not be killed, but the device is
running slightly low on memory. The system may start to kill processes based on the Least
Recently Used (LRU) list.
10: The application is running properly and will not be killed, but the device is
running extremely low on memory. Your application should release some unnecessary resources
to improve system performance, which accordingly improves the application performance.
15: The application is running properly, but the system has killed most of the
cached processes based on the LRU list. In this case, your application should release as
many unnecessary resources as possible. Otherwise, the system may continue to kill all the
cached processes and start to kill some processes that should be kept running, for example,
services running in the background.
20: The application UI is hidden, for example, because the user touched the Home
key on the device. Your application should releases resources allocated for UI display to
free up memory.
40: The device is running low on memory and your application is around the top of
the LRU list. The system is not likely to kill your application. To keep your application
processes in the cache for a longer time, your application should increase available system
memory by releasing some resources that can be easily restored. In this way, your
application is able to smoothly return to the foreground, instead of being restarted.
60: The device is running extremely low on memory and your application is around
the middle of the LRU list. Your application may be killed later if no more memory is
freed up.
80: The device is running extremely low on memory and your application is at the
end of the LRU list. The system is most likely to kill your application first. In this case,
your application should release all resources that can be released.
public void onReconnect(Intent intent)
The Service ability must have been started but not been destroyed, that is, startAbility(ohos.aafwk.content.Intent) has been
called but stopAbility(ohos.aafwk.content.Intent) has not.
intent - Indicates the intent of the Service ability being connected.public void onMissionDeleted(Intent intent)
intent - Indicates the original Intent used for starting the deleted mission.protected void onAbilityResult(int requestCode,
int resultCode,
Intent resultData)
startAbilityForResult(ohos.aafwk.content.Intent,int) is called to start an ability and the result is returned.
This method is called only on Page abilities. You can start a new ability to perform some calculations and use
setResult(int,ohos.aafwk.content.Intent) to return the calculation result. Then the system calls back the current
method to use the returned data to execute its own logic.
requestCode - Indicates the request code returned after the ability is started. You can define the request
code to identify the results returned by abilities. The value ranges from 0 to 65535.resultCode - Indicates the result code returned after the ability is started. You can define the result
code to identify an error.resultData - Indicates the data returned after the ability is started. You can define the data returned.
The value can be null.protected AbilityForm onCreateForm()
AbilityForm object.
If a Page ability needs to be displayed as an AbilityForm in other abilities, override this method to
return an AbilityForm object. By default, null is returned.
AbilityForm object.protected ProviderFormInfo onCreateForm(Intent intent)
ProviderFormInfo object.
You must override this method if your ability will serve as a form provider to provide a form for clients.
The default implementation returns null.
intent - Indicates the detailed information for creating a ProviderFormInfo.
The Intent object must include the form ID, form name, and grid style of the form,
which can be obtained from AbilitySlice#PARAM_FORM_IDENTITY_KEY,
AbilitySlice#PARAM_FORM_NAME_KEY, and AbilitySlice#PARAM_FORM_DIMENSION_KEY,
respectively. Such form information must be managed as persistent data for further form
acquisition, update, and deletion.ProviderFormInfo object.@Deprecated protected void onDeleteForm(int formId)
onDeleteForm(long).formId - Indicates the ID of the deleted form.protected void onDeleteForm(long formId)
formId - Indicates the ID of the deleted form.@Deprecated protected void onUpdateForm(int formId)
onUpdateForm(long).formId - Indicates the ID of the form to update.protected void onUpdateForm(long formId)
formId - Indicates the ID of the form to update.protected void onEventNotify(Map<Long,Integer> formEvents)
formEvents - Indicates the form events occurred. The key in the Map object indicates the form ID,
and the value indicates the event type, which can be either FORM_VISIBLE
or FORM_INVISIBLE. FORM_VISIBLE means that the form becomes visible,
and FORM_INVISIBLE means that the form becomes invisible.protected void onCastTempForm(long formId)
formId - Indicates the ID of the form.@Deprecated protected void onTriggerFormEvent(int formId, String message)
onTriggerFormEvent(long,java.lang.String).You must override this method to define the work to do after the message event is triggered if
a message event is configured.
You can define a message event for a component on a JS form. When the user touches the particular component
on the form, your application, as the form provider, will be notified and receive the value of
the params field contained in the event.
formId - Indicates the ID of the form on which the message event is triggered, which is provided by
the client to the form provider.message - Indicates the value of the params field of the message event. This parameter is
used to identify the specific component on which the event is triggered.protected void onTriggerFormEvent(long formId,
String message)
You must override this method to define the work to do after the message event is triggered if
a message event is configured.
You can define a message event for a component on a JS form. When the user touches the particular component
on the form, your application, as the form provider, will be notified and receive the value of
the params field contained in the event.
formId - Indicates the ID of the form on which the message event is triggered, which is provided by
the client to the form provider.message - Indicates the value of the params field of the message event. This parameter is
used to identify the specific component on which the event is triggered.@Deprecated public boolean updateForm(int formId, ComponentProvider component) throws FormException
updateForm(long,ohos.agp.components.ComponentProvider).This method is called by a form provider to update Java form data as needed.
formId - Indicates the ID of the Java form to update.component - Indicates the ComponentProvider object used to update the Java form displayed
on the client.true if the update is successful; returns false otherwise.FormException - Throws this exception if the form fails to be obtained due to any of the following reasons:
formID or formBindingData is invalid. The value of formID must be larger
than 0, and formBindingData must not be null.public boolean updateForm(long formId,
ComponentProvider component)
throws FormException
This method is called by a form provider to update Java form data as needed.
formId - Indicates the ID of the Java form to update.component - Indicates the ComponentProvider object used to update the Java form displayed
on the client.true if the update is successful; returns false otherwise.FormException - Throws this exception if the form fails to be obtained due to any of the following reasons:
formID or formBindingData is invalid. The value of formID must be larger
than 0, and formBindingData must not be null.@Deprecated public boolean updateForm(int formId, FormBindingData formBindingData) throws FormException
updateForm(long,ohos.aafwk.ability.FormBindingData).This method is called by a form provider to update JS form data as needed.
formId - Indicates the ID of the JS form to update.formBindingData - Indicates the FormBindingData object used to update the JS form displayed
on the client.true if the update is successful; returns false otherwise.FormException - Throws this exception if the form fails to be obtained due to any of the following reasons:
formID or component is invalid. The value of formID must be larger than 0,
and component must not be null.public boolean updateForm(long formId,
FormBindingData formBindingData)
throws FormException
This method is called by a form provider to update JS form data as needed.
formId - Indicates the ID of the JS form to update.formBindingData - Indicates the FormBindingData object used to update the JS form displayed
on the client.true if the update is successful; returns false otherwise.FormException - Throws this exception if the form fails to be obtained due to any of the following reasons:
formID or component is invalid. The value of formID must be larger than 0,
and component must not be null.public boolean setFormNextRefreshTime(long formId,
long nextTime)
throws FormException
This method is provided for form providers.
formId - Indicates the ID of the form for which you want to set the refresh time.nextTime - Indicates the interval between the current time and the next refresh time in seconds.
The smallest value is 300.true if the setting is successful; returns false otherwise.FormException - Throws this exception if any of the cases occur:
formId is less than or equal to 0, or the value of nextTime
is less than 300.protected FormState onAcquireFormState(Intent intent)
FormState object.
You must override this callback if you want this ability to return the actual form state. Otherwise,
this method returns FormState#DEFAULT by default.
intent - Indicates the description of the form for which the FormState is obtained. The description
covers the bundle name, ability name, module name, form name, and form dimensions,
which can be obtained through ElementName#getBundleName(),
ElementName#getAbilityName(), AbilitySlice#PARAM_MODULE_NAME_KEY,
AbilitySlice#PARAM_FORM_NAME_KEY,
and AbilitySlice#PARAM_FORM_DIMENSION_KEY respectively.FormState object.public void onSaveAbilityState(PacMap outState)
This method is called when the system determines that the ability may be destroyed in an unexpected situation, for example, when the screen orientation changes or the user touches the Home key. Generally, this method is used only to save temporary states.
outState - Indicates the PacMap object used for storing user data and states. This
parameter cannot be null.public Object onStoreDataWhenConfigChange()
AbilityContext.getLastStoredDataWhenConfigChanged() to obtain the saved data in a new ability instance.public Uri onSetCaller()
null.public void onRestoreAbilityState(PacMap inState)
This method is called if an ability was destroyed at a certain time due to resource reclaim or was
unexpectedly destroyed and the onSaveAbilityState(ohos.utils.PacMap) method was called to save its user data and
states. Generally, this method is called after the onStart(ohos.aafwk.content.Intent) method.
inState - Indicates the PacMap object used for storing data and states. This
parameter can not be null.public void onRequestPermissionsFromUserResult(int requestCode,
String[] permissions,
int[] grantResults)
AbilityContext.requestPermissionsFromUser(java.lang.String[],int).requestCode - Indicates the request code passed to this method from
AbilityContext.requestPermissionsFromUser(java.lang.String[],int).permissions - Indicates the list of permissions requested by using
AbilityContext.requestPermissionsFromUser(java.lang.String[],int). This parameter cannot be null.grantResults - Indicates the granting results of the corresponding permissions requested using
AbilityContext.requestPermissionsFromUser(java.lang.String[],int). The value 0 indicates
that a permission is granted, and the value -1 indicates not.public CharSequence onNewDescription()
public void onLeaveForeground()
public void onEventDispatch()
onLeaveForeground(), is designed to help abilities intelligently
manage status bar notifications. Specifically, they help abilities determine when to cancel a notification.public final void startAbility(Intent intent) throws IllegalArgumentException, IllegalStateException
A Page or Service ability uses this method to start a specific ability. The system locates the target ability
from installed abilities based on the value of the intent parameter and then starts it. You can specify
the ability to start using the intent parameter.
You can start a new Service ability even if the application hosting the ability is not started
by adding a flag of Intent#FLAG_START_FOREGROUND_ABILITY.
intent - Indicates the ability to start.IllegalArgumentException - Throws this exception if the input parameter is null.IllegalStateException - Throws this exception if the ability is not initialized.public final void startAbility(Intent intent, IAbilityStartCallback callback) throws IllegalArgumentException, IllegalStateException
A Page or Service ability uses this method to start a specific ability. The system locates the target ability
from installed abilities based on the value of the intent parameter and then starts it. You can specify
the ability to start using the intent parameter.
You can start a new Service ability even if the application hosting the ability is not started
by adding a flag of Intent#FLAG_START_FOREGROUND_ABILITY.
intent - Indicates the ability to start.callback - Inidcates the callback to start.IllegalArgumentException - Throws this exception if the input parameter is null.IllegalStateException - Throws this exception if the ability is not initialized.public void onTopActiveAbilityChanged(boolean topActive)
topActive - Specifies whether this ability is moved to or removed from the top of the stack.
The value true indicates that it is moved to the top, and false indicates
that it is removed from the top of the stack.public final void startAbility(Intent intent, AbilityStartSetting abilityStartSetting) throws IllegalArgumentException, IllegalStateException
A Page or Service ability uses this method to start a specific ability. The system locates the target ability
from installed abilities based on the value of the intent parameter and then starts it. You can specify
the ability to start using the intent parameter.
You can start a new Service ability even if the application hosting the ability is not started
by adding a flag of Intent#FLAG_START_FOREGROUND_ABILITY.
intent - Indicates the ability to start.abilityStartSetting - Indicates the setting ability used to start.IllegalArgumentException - Throws this exception if the input parameter is null.IllegalStateException - Throws this exception if the ability is not initialized.public final void startAbility(Intent intent, AbilityStartSetting abilityStartSetting, AbilityTransitionUtils abilityTransitionUtils) throws IllegalArgumentException, IllegalStateException
A Page or Service ability uses this method to start a specific ability. The system locates the target ability
from installed abilities based on the value of the intent parameter and then starts it. You can specify
the ability to start using the intent parameter.
You can start a new Service ability even if the application hosting the ability is not started
by adding a flag of Intent#FLAG_START_FOREGROUND_ABILITY.
intent - Indicates the ability to start.abilityStartSetting - Indicates the setting ability used to start.abilityTransitionUtils - Indicates the setting ability used to start.IllegalArgumentException - Throws this exception if the input parameter is null.IllegalStateException - Throws this exception if the ability is not initialized.public final void startAbilityForResult(Intent intent, int requestCode, AbilityStartSetting abilityStartSetting) throws IllegalArgumentException, IllegalStateException
When the ability is destroyed, onAbilityResult(int,int,ohos.aafwk.content.Intent) is called and the returned
requestCode is transferred to the current method. The given requestCode is customized and
cannot be a negative number.
intent - Indicates the ability to start.requestCode - Indicates the request code returned after the ability is started. You can define the request
code to identify the results returned by abilities. The value ranges from 0 to 65535.abilityStartSetting - Indicates the setting ability used to start.IllegalArgumentException - Throws this exception if the input parameter is invalid.IllegalStateException - Throws this exception if the ability is not initialized.startAbility(Intent),
onAbilityResult(int, int, Intent),
setResult(int, Intent)public final void startAbilityForResult(Intent intent, int requestCode) throws IllegalArgumentException, IllegalStateException
When the ability is destroyed, onAbilityResult(int,int,ohos.aafwk.content.Intent) is called and the returned
requestCode is transferred to the current method. The given requestCode is customized and
cannot be a negative number.
intent - Indicates the ability to start.requestCode - Indicates the request code returned after the ability is started. You can define the request
code to identify the results returned by abilities. The value ranges from 0 to 65535.IllegalArgumentException - Throws this exception if the input parameter is invalid.IllegalStateException - Throws this exception if the ability is not initialized.startAbility(Intent),
onAbilityResult(int, int, Intent),
setResult(int, Intent)public final void setResult(int resultCode,
Intent resultData)
When a Page ability is destroyed, the caller overrides the
AbilitySlice#onAbilityResult(int, int, Intent) method to receive the result set in the current method.
This method can be called only after the ability has been initialized.
resultCode - Indicates the result code returned after the ability is destroyed. You can define the result
code to identify an error.resultData - Indicates the data returned after the ability is destroyed. You can define the data returned.
This parameter can be null.IllegalStateException - Throws this exception if this ability is not a Page ability or the ability is not
initialized.public final void terminateAbility()
After a Page or Service ability performs all operations, it can use this method to destroy itself to free up memory. This method can be called only after the ability is initialized.
terminateAbility 在接口中 ContextterminateAbility 在类中 AbilityContextIllegalStateException - Throws this exception if the ability is not initialized.Context.terminateAbility()public final boolean stopAbility(Intent intent)
stopAbility 在接口中 ContextstopAbility 在类中 AbilityContextintent - Indicates information about the Service ability.true if the Service ability is destroyed; returns false otherwise.Context.stopAbility(Intent)public final void setMainRoute(String entry) throws IllegalStateException
You can call this method to set the default route of the ability, that is, the AbilitySlice to
present. This method can be used only for Page abilities.
Note: If you do not set a default route in onStart(ohos.aafwk.content.Intent), the startup will fail.
entry - Indicates the main entry, which is the fully qualified name of your AbilitySlice class.IllegalStateException - Throws this exception if this ability is not a Page ability or is not initialized.public final void addActionRoute(String action, String entry) throws IllegalStateException
AbilitySlice.
By binding an action, you can set different action parameters in Intent to present different initial
pages. You must register actions in the profile file.
action - Indicates the action to bind.entry - Indicates the entry, which is the fully qualified name of your AbilitySlice class.IllegalStateException - Throws this exception if this ability is not a Page ability or is not initialized.public final void setWindowBackgroundColor(int red,
int green,
int blue)
throws IllegalStateException
red - The value ranges from 0 to 255.green - The value ranges from 0 to 255.blue - The value ranges from 0 to 255.IllegalStateException - Throws this exception if the ability is not initialized.public final void keepBackgroundRunning(int id,
NotificationRequest notificationRequest)
To use this method, you need to request the ohos.permission.KEEP_BACKGROUND_RUNNING permission
from the system. The ohos.permission.KEEP_BACKGROUND_RUNNING permission is of the normal
level.
This method can be called only by Service abilities after the onStart(ohos.aafwk.content.Intent) method is
called.
id - Identifies the notification bar information.notificationRequest - Indicates the NotificationRequest instance containing information for
displaying a notification bar.IllegalStateException - Throws this exception if this ability is not a Service ability or is
not initialized.IllegalArgumentException - Throws this exception in the passed NotificationRequest instance is
null.ProfileMissingConfigException - Throws this exception if param backgroundModes is not set in profile.public final void cancelBackgroundRunning()
throws IllegalStateException
This method can be called only by Service abilities when the onStop() method is
called.
IllegalStateException - Throws this exception if this ability is not a Service ability or is
not initialized.public final void continueAbility()
throws IllegalStateException,
UnsupportedOperationException
If there are multiple candidate devices, a pop-up will be displayed for users to choose the desired one.
The ability to migrate and its ability slices must implement the IAbilityContinuation interface.
Otherwise, an exception is thrown, indicating that the ability does not support migration.
IllegalStateException - Throws this exception if this ability is not initialized or is in a state
where this operation is not allowed, for example, it is being migrated.UnsupportedOperationException - Throws this exception if this ability does not implement the
IAbilityContinuation interface.public final void continueAbility(String deviceId) throws IllegalStateException, UnsupportedOperationException
The ability to migrate and its ability slices must implement the IAbilityContinuation interface.
Otherwise, an exception is thrown, indicating that the ability does not support migration.
deviceId - Indicates the ID of the target device where this ability will be migrated to. If this parameter
is null, this method has the same effect as continueAbility().IllegalStateException - Throws this exception if this ability is not initialized or is in a state
where this operation is not allowed, for example, it is being migrated.UnsupportedOperationException - Throws this exception if this ability does not implement the
IAbilityContinuation interface.public final void continueAbilityReversibly()
throws IllegalStateException,
UnsupportedOperationException
reverseContinueAbility().
If there are multiple candidate devices, a pop-up will be displayed for users to choose the desired one.
The ability to migrate and its ability slices must implement the IAbilityContinuation interface.
Otherwise, an exception is thrown, indicating that the ability does not support migration.
IllegalStateException - Throws this exception if this ability is not initialized or is in a state
where this operation is not allowed, for example, it is being migrated.UnsupportedOperationException - Throws this exception if this ability does not implement the
IAbilityContinuation interface.public final void continueAbilityReversibly(String deviceId) throws IllegalStateException, UnsupportedOperationException
reverseContinueAbility().
The ability to migrate and its ability slices must implement the IAbilityContinuation interface.
Otherwise, an exception is thrown, indicating that the ability does not support migration.
deviceId - Indicates the ID of the target device where this ability will be migrated to. If this parameter
is null, this method has the same effect as continueAbilityReversibly().IllegalStateException - Throws this exception if this ability is not initialized or is in a state
where this operation is not allowed, for example, it is being migrated.UnsupportedOperationException - Throws this exception if this ability does not implement the
IAbilityContinuation interface.public final boolean reverseContinueAbility()
throws IllegalStateException,
UnsupportedOperationException
true if the migration request is successful; returns false otherwise.IllegalStateException - Throws this exception if this ability was not involved in a reversible
migration process, or if it is in a state where this operation is not
allowed, for example, it is being migrated back.UnsupportedOperationException - Throws this exception if this ability does not implement the
IAbilityContinuation interface.public final ContinuationState getContinuationState() throws UnsupportedOperationException
UnsupportedOperationException - Throws this exception if this ability does not implement the
IAbilityContinuation interface.public final String getOriginalDeviceId() throws UnsupportedOperationException
You can call this method on the target remote device to obtain the source device ID after you have initiated a reversible migration process that allows the ability to be migrated back from the target device to the source device.
UnsupportedOperationException - Throws this exception if this ability does not implement the
IAbilityContinuation interface.public final void setAbilitySliceAnimator(AbilitySliceAnimator abilitySliceAnimator) throws IllegalStateException
AbilitySlice instances of the current ability.
You can use the AbilitySliceAnimator class to define animation properties. Currently, only translation
is supported. Rotation, gradient, and scale operations will be supported later. The properties can be set by
calling the onStart(ohos.aafwk.content.Intent) method of the ability.
abilitySliceAnimator - Indicates the animation properties, such as translate, rotate, or alpha.
If this parameter is null, the transition animation is disabled.IllegalStateException - Throws this exception if the ability is not initialized.public boolean isTerminating()
An ability is being destroyed if you called terminateAbility() on it or someone else requested to
destroy it.
true if the current ability is being destroyed; returns false otherwise.terminateAbility()public void setIntent(Intent intent)
Intent object that can be obtained by calling getIntent().
This method does not copy the given Intent object, instead, it holds a reference to the given object
and takes effect directly on it. This method is often used with onNewIntent(ohos.aafwk.content.Intent).
intent - Indicates the Intent object to set.public Intent getIntent()
Intent object that starts this ability.Intent object that starts this ability.public boolean hasWindowFocus()
true if this ability currently has window focus; returns false otherwise.public Component getCurrentFocus()
Component object that has window focus if any is found;
returns null otherwise.public void onWindowFocusChanged(boolean hasFocus)
The focus state refers to the global state, which is independent of the ability lifecycle states. Although
the lifecycle state change of an ability may lead to a focus change (for example, onStop() may cause
the ability to lose window focus), there is no particular sequence between this callback and other lifecycle
callbacks such as onBackground().
Generally, the ability in the foreground will have window focus. The ability will lose focus when another dialog box or pop-up window is displayed. The ability will also lose focus when a system-level window (such as the status bar or a system alarm) is displayed.
hasFocus - Specifies whether this ability has focus.public boolean setSwipeToDismiss(boolean isEnabled)
isEnabled - Specifies whether a window should dismiss when swiped away.true if set successfully; returns false otherwise.public Uri normalizeUri(Uri uri)
uri that refer to the Data ability into a normalized URI. A normalized URI can be
used across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability
even if the context has changed.
If you implement URI normalization for a Data ability, you must also implement denormalizeUri(ohos.utils.net.Uri)
to enable URI denormalization. After this feature is enabled, URIs passed to any method that is called on the
Data ability must require normalization verification and denormalization.
The default implementation of this method returns null, indicating that this Data ability does
not support URI normalization.
uri - Indicates the Uri object to normalize.Uri object if the Data ability supports URI normalization;
returns null otherwise.denormalizeUri(ohos.utils.net.Uri)public Uri denormalizeUri(Uri uri)
uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
The default implementation of this method returns the original URI passed to it.uri - uri Indicates the Uri object to denormalize.Uri object if the denormalization is successful; returns the original
Uri passed to this method if there is nothing to do; returns null if the data identified by
the original Uri cannot be found in the current environment.normalizeUri(ohos.utils.net.Uri)public void dispatchAccessibilityEventInfo(AccessibilityEventInfo info)
info - Indicates the accessibility event information to add.public boolean reload(Uri uri, PacMap extras)
The default implementation of this method returns false. You must implement this method in the child
class of your Data Ability if you want to use it.
uri - Indicates the position where the data is to reload.extras - Indicates the additional parameters contained in the PacMap object to be passed
in this call.true if the data is successfully reloaded; returns false otherwise.public void setVolumeTypeAdjustedByKey(int volumeType)
volumeType - Indicates the AudioManager.AudioVolumeType to set.public int getVolumeTypeAdjustedByKey()
AudioManager.AudioVolumeType.public String getAbilityName()
public final AbilityLifecycleExecutor.LifecycleState getState()
public void executeOperation(DataAbilityOperation operation, DataAbilityResult[] refResults, int refIndex) throws OperationExecuteException
Ability#executeBatch(ArrayList) for executing batch operations.operation - Indicates the operation to execute.refResults - Indicates a set of results of the batch operations.refIndex - Indicates the index of the current operation result in the batch operation results.OperationExecuteException - if execute this operation exception, will throw it.public ValuesBucket parseValuesBucketReference(DataAbilityResult[] refResults, DataAbilityOperation operation, int numRefs) throws OperationExecuteException
ValuesBucket object by parsing the database operation results
based on the specified operation.refResults - Indicates the result set of database operations. This parameter cannot be null.operation - Indicates the database operation. This parameter cannot be null.numRefs - Indicates the index of a valid database operation specified by operation.
The index is used to locate a particular database operation result in refResults.ValuesBucket object
parsed from the specified database operation result.OperationExecuteException - Throws this exception if an input parameter is invalid.public DataAbilityPredicates parsePredictionArgsReference(DataAbilityResult[] refResults, DataAbilityOperation operation, int numRef) throws OperationExecuteException
DataAbilityPredicates object by parsing the database
operation results based on the specified operation.refResults - Indicates the result set of database operations. This parameter cannot be null.operation - Indicates the database operation. This parameter cannot be null.numRef - Indicates the index of a valid database operation specified by operation.
The index is used to locate a particular database operation result in refResults.DataAbilityPredicates object
parsed from the specified database operation result.OperationExecuteException - Throws this exception if an input parameter is invalid.public final void startAssistAbility(Intent intent, IAssistanceChannel channel)
You need to specify the device ID, bundle name, and ability name of the peer ability through
intent.
Both parties in a collaboration session must be Page abilities, which belong to the same application
and share the bundle name and signature. The peer ability needs to implement the IAssistanceChannel
API.
This method works only when the devices involved in the collaboration session are connected through the same WLAN.
The collaboration result is sent to your application through the IAssistanceChannel callback.
Permissions: SystemPermission.DISTRIBUTED_DATASYNC
intent - Indicates the ability with which a collaboration session is to be established.channel - Indicates the channel used to receive the collaboration session establishment result sent using
the IAssistanceChannel callback.public final int stopAssistAbility(AbilityAgent agent)
You need to pass AbilityAgent to specify the ability from which you want to disconnect the
collaboration session. After your application successfully calls Ability#startAssistAbility to
establish a collaboration session, the framework calls IAssistanceChannel#onConnected to notify
your application of the result. After the collaboration session is disconnected, the framework uses
IAssistanceChannel#onDisconnected to notify your app.
To cancel establishment of a collaboration session, call this method and pass null.
agent - Indicates the ability from which this collaboration session is to be disconnected.AssistantCode#OK
if the disconnecting succeeds; returns an error code defined in AssistantCode otherwise.public void setAdmissionTransitionObject(Transition transition)
transition - Transition Animation Type.public void setBackTransitionObject(Transition transition)
transition - Transition Animation Type.public void setQuitTransitionObject(Transition transition)
transition - Transition Animation Type.public void setReadmissionTransitionObject(Transition transition)
transition - v.public void setSharedItemAdmissionTransitionObject(Transition transition)
transition - Transition Animation Type.public void setSharedItemBackTransitionObject(Transition transition)
transition - Transition Animation Type.public void setSharedItemQuitTransitionObject(Transition transition)
transition - Transition Animation Type.public void setSharedItemReadmissionTransitionObject(Transition transition)
transition - Transition Animation Type.public Transition getAdmissionTransitionObject()
public Transition getBackTransitionObject()
public Transition getQuitTransitionObject()
public Transition getReadmissionTransitionObject()
public Transition getSharedItemAdmissionTransitionObject()
public Transition getSharedItemBackTransitionObject()
public Transition getSharedItemQuitTransitionObject()
public Transition getSharedItemReadmissionTransitionObject()
public void setAdmissionTransitionConcurEnabled(boolean enabled)
enabled - Indicates an instance of the animation process control class.public boolean getAdmissionTransitionConcurEnabled()
public void setBackTransitionConcurEnabled(boolean enabled)
enabled - rAdmissionTransition Indicates an instance of the animation process control class.public boolean getBackTransitionConcurEnabled()