ILifecycle, Contextpublic class AbilitySlice extends AbilityContext implements ILifecycle
Ability using the Page template, AbilitySlice provides an ability with
a carrier for service logic and UI display.
An ability can have multiple ability slices. You must override the Ability#onStart(Intent) method to
specify the default ability slice. This default route is specified by using Ability#setMainRoute(String)
.
You can inherit the AbilitySlice class to implement your own ability slices and set their UI in the
onStart(ohos.aafwk.content.Intent) method. The UI can be set by using setUIContent(ohos.agp.components.ComponentContainer) or
setUIContent(int). Generally, in the entire lifecycle of an ability slice, the UI needs to be set only
once. Example code:
public class MyAbilitySlice extends AbilitySlice {
protected void onStart(Intent intent) {
super.onStart(intent);
// setup UI content from a layout resource
setUIContent(R.res.layout);
}
}
You can use the present(ohos.aafwk.ability.AbilitySlice,ohos.aafwk.content.Intent) method to present a new ability slice or use the
startAbility(ohos.aafwk.content.Intent) method to start a new ability.
An ability slice must always be hosted in an ability, and its lifecycle changes along with that of the ability. An ability slice also has its independent lifecycle changes, which occur during the switching of ability slices.
Note: In most cases, you are responsible for creating and maintaining ability slice instances. However,
the system creates instances in certain scenarios. For example, the system creates an ability slice instance
during the first start of an ability. This requires that all AbilitySlice child classes have a default
no-argument constructor. As defined in Java, the compiler provides a default no-argument constructor for the class
only if you do not explicitly declare a parameterized constructor. Therefore, when overriding a
AbilitySlice child class, you must explicitly declare a no-argument constructor if your implementation has
a parameterized constructor.
You can specify multiple action entries and a default main entry for an ability. Each entry represents the
capabilities and UI that the ability can provide. When an ability is started, the system matches the
action field in the transferred Intent against the entries defined. If a specified ability slice
is found, the system starts it. If the action field is not specified in the transferred Intent or
the action field in the transferred Intent does not match any entry defined, the default ability
slice is displayed.
The code below shows how to set the entry to an ability:
public class MainAbility extends Ability {
public void onStart(Intent intent) {
super.onStart(intent);
// set the main entry
setMainRoute(MainSlice.class.getName());
// add action for ability
addActionRoute("action.pay", PaySlice.class.getName());
addActionRoute("action.scan", ScanSlice.class.getName());
}
}
The preceding code defines only the entry route at runtime. To expose the ability's capabilities to other
abilities, you must register the action field in the configuration file config.json.
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",
"skills"[
{
"actions":[
"action.pay",
"action.scan"
]
}
]
...
}
]
...
}
}
After the supported actions are registered in the preceding way, other abilities can use your ability through the specified actions and directly open the corresponding ability slices. Example code:
Intent intent = new Intent();
Operation operation = new Intent.OperationBuilder()
.withAction("action.pay")
.withDeviceId("")
.withBundleName("xxx")
.withAbilityName("yyy")
.build();
intent.setOperation(operation);
startAbility(intent);
An ability slice's lifecycle is bound to the ability that hosts it. An ability slice has the same lifecycle states and lifecycle callback methods as the host ability. Once the lifecycle state of an ability changes, its ability slices undergo the same change, and the same callback method is called. An ability slice can also have its independent lifecycle changes. This independent change occurs during the switching of the ability slices in the ability. However, such a switching does not affect the host ability's lifecycle.
An ability slice has the following four lifecycle states:
Similar to an ability, an ability slice provides the following lifecycle callback methods. You can override them.
public class MainAbilitySlice extends AbilitySlice {
protected void onStart(Intent intent);
protected void onActive();
protected void onInactive();
protected void onForeground(Intent intent);
protected void onBackground();
protected void onStop();
}
The figure below shows a complete lifecycle of an ability slice. An ability slice can be in only one state at any time. Not all states support direct transition.

Note: The onStart(ohos.aafwk.content.Intent) method can be called only once in the entire lifecycle.
The meaning of each lifecycle callback method and some best practice suggestions is provided below.
onStart(ohos.aafwk.content.Intent): You must implement this method for UI initialization settings, for example,
setUIContent(int).
This method can be called only once in the entire lifecycle. The caller may carry some customized key-values
by using Intent class, and obtain these parameters through the methods provided by intent.
onActive(): This method is called back when an ability slice returns to the Active state.
After the callback, the UI is interactive.
onInactive(): This method is called back when an ability slice is completely or partially covered.
After the callback, the UI is not interactive.
onForeground(ohos.aafwk.content.Intent) ()}: This method is called back when an ability slice returns to the
foreground. The interaction logic of the application can be restored or initialized in the callback. If a new
customized parameter needs to be specified when the ability slice returns to the foreground, you can transfer a new
intent parameter.
onBackground(): This method is called back when an ability slice has entered the background. In
this state, you cannot perform background tasks for a long time, since the system may stop the running of a
background program at any time.
onStop(): This method is called back to destroy an ability slice. You can use this method to
reclaim resources.
You can use the present(ohos.aafwk.ability.AbilitySlice,ohos.aafwk.content.Intent) method to present a new ability slice,
and transfer customized parameters using Intent. Example code:
Button button = new Button(this);
button.setClickedListener(listener -> {
AbilitySlice targetSlice = new MyAbilitySlice();
Intent intent = new Intent();
intent.setParam("value", 10);
present(targetSlice, intent);
});
Note: A maximum of 1024 ability slices in an ability can be presented simultaneously. If you attempt to present the 1025th ability slice, the system will forcibly crash the ability. To avoid this situation, you must improve the code if a large number of ability slices need to be presented simultaneously.
SystemCapability.Aafwk#ABILITY| 限定符和类型 | 类 | 说明 |
|---|---|---|
static interface |
AbilitySlice.FormCallback |
Provides callbacks that will be invoked when a
Form instance is obtained or when the Form
provider is uninstalled. |
| 限定符和类型 | 字段 | 说明 |
|---|---|---|
static String |
PARAM_FORM_CUSTOMIZE_KEY |
Indicates the key used for passing custom data to the form provider when you call
{@link #acquireForm(ohos.aafwk.content.Intent,ohos.aafwk.ability.AbilitySlice.FormCallback),
which is represented as
intent.setParam(PARAM_FORM_CUSTOMIZE_KEY, intentParams). |
static String |
PARAM_FORM_DIMENSION_KEY |
Indicates the key specifying the grid style of the form to be obtained, which is represented as
intent.setParam(PARAM_FORM_DIMENSION_KEY, 1). |
static String |
PARAM_FORM_HEIGHT_KEY |
Indicates the key specifying the height of the form to be obtained, which is represented as
intent.setParam(PARAM_FORM_HEIGHT_KEY, 400). |
static String |
PARAM_FORM_ID_KEY |
已过时。
This change is effective since API version 5. Replaced by
PARAM_FORM_IDENTITY_KEY. |
static String |
PARAM_FORM_IDENTITY_KEY |
Indicates the key specifying the ID of the form to be obtained, which is represented as
intent.setParam(PARAM_FORM_IDENTITY_KEY, 1L). |
static String |
PARAM_FORM_NAME_KEY |
Indicates the key specifying the name of the form to be obtained, which is represented as
intent.setParam(PARAM_FORM_NAME_KEY, "formName"). |
static String |
PARAM_FORM_TEMPORARY_KEY |
Indicates the key specifying whether a form is temporary, which is represented as
intent.setParam(PARAM_FORM_TEMPORARY_KEY, true). |
static String |
PARAM_FORM_WIDTH_KEY |
Indicates the key specifying the width of the form to be obtained, which is represented as
intent.setParam(PARAM_FORM_WIDTH_KEY, 800). |
static String |
PARAM_MODULE_NAME_KEY |
Indicates the key specifying the name of the module to which the form to be obtained belongs, which is
represented as
intent.setParam(PARAM_MODULE_NAME_KEY, "formEntry"). |
CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_RESOUCE_ONLY, CONTEXT_RESTRICTED, MODE_APPEND, MODE_PRIVATE| 构造器 | 说明 |
|---|---|
AbilitySlice() |
| 限定符和类型 | 方法 | 说明 |
|---|---|---|
boolean |
acquireAbilityFormAsync(Intent intent,
AbilityForm.OnAcquiredCallback acquiredCallback) |
Requests the
AbilityForm instance provided by the target ability. |
boolean |
acquireForm(Intent intent,
AbilitySlice.FormCallback callback) |
Obtains a specified form that matches the application bundle name, module name, form name, form grid style, and
other related information specified in the passed
Intent. |
void |
acquireFormState(Intent intent,
AbilitySlice.FormCallback callback) |
Obtains the state of the form that matches the application bundle name, module name, form name, form grid style,
and other related information specified in the passed
intent. |
boolean |
castTempForm(long formId) |
Converts a specified temporary form that has been obtained by the application into a normal form.
|
int |
checkAndDeleteInvalidForms(List<Long> persistedIds) |
Checks for and deletes invalid forms of the application in the Form Manager Service based on the list of valid
form IDs passed.
|
boolean |
connectAbility(Intent intent,
IAbilityConnection conn) |
Connects the host ability to an ability that uses the Service template.
|
void |
continueAbility() |
Migrates the host ability to another device on the same distributed network.
|
void |
continueAbility(String deviceId) |
Migrates the host ability to the given device on the same distributed network.
|
void |
continueAbilityReversibly() |
Migrates the host ability to another device on the same distributed network in a reversible way that allows the
ability to be migrated back to the local device through
reverseContinueAbility(). |
void |
continueAbilityReversibly(String deviceId) |
Migrates the host ability to another device on the same distributed network in a reversible way that allows the
ability to be migrated back to the local device through
reverseContinueAbility(). |
boolean |
deleteForm(int formId) |
已过时。
This change is effective since API version 5. Replaced by
deleteForm(long). |
boolean |
deleteForm(long formId) |
Deletes an obtained form by its ID.
|
void |
disconnectAbility(IAbilityConnection conn) |
Disconnects the host ability from an ability that uses the Service template.
|
<T extends Component> |
findComponentById(int resId) |
Finds a component in the XML file based on the resource ID.
|
Ability |
getAbility() |
Obtains the host ability of this
AbilitySlice. |
List<FormInfo> |
getAllForms() |
已过时。
This change is effective since API version 5. Replaced by
getAllFormsInfo(). |
List<FormInfo> |
getAllFormsInfo() |
Obtains the
FormInfo objects provided by all applications on the device. |
IContinuationRegisterManager |
getContinuationRegisterManager() |
Obtains an
IContinuationRegisterManager object. |
ContinuationState |
getContinuationState() |
Obtains the migration state of the host ability.
|
List<FormInfo> |
getFormsByApp(String bundleName) |
已过时。
This change is effective since API version 5. Replaced by
getFormsInfoByApp(java.lang.String). |
List<FormInfo> |
getFormsByModule(String bundleName,
String moduleName) |
已过时。
This change is effective since API version 5. Replaced by
getFormsInfoByModule(java.lang.String,java.lang.String). |
List<FormInfo> |
getFormsInfoByApp(String bundleName) |
Obtains the
FormInfo objects provided by a specified application on the device. |
List<FormInfo> |
getFormsInfoByModule(String bundleName,
String moduleName) |
Obtains the
FormInfo objects provided by a specified application module on the device. |
WindowManager.LayoutConfig |
getLayoutParams() |
Obtains window layout parameters of an ability.
|
Lifecycle |
getLifecycle() |
Obtains the
Lifecycle object of the current ability slice. |
String |
getOriginalDeviceId() |
Obtains the ID of the source device from which the host ability is migrated.
|
AbilitySliceLifecycleExecutor.LifecycleState |
getState() |
Obtains the lifecycle state of this ability slice.
|
Window |
getWindow() |
Obtains the window corresponding to the current ability.
|
void |
notifyInvisibleForms(List<Long> formIds) |
Sends a notification to the form framework to make the specified forms invisible.
|
void |
notifyVisibleForms(List<Long> formIds) |
Sends a notification to the form framework to make the specified forms visible.
|
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 void |
onActive() |
Called back when an ability slice enters the ACTIVE state.
|
protected void |
onBackground() |
Called back when an ability slice enters the BACKGROUND state.
|
protected void |
onBackPressed() |
Called back when the Back key is pressed.
|
protected void |
onForeground(Intent intent) |
Called back when the state of an ability slice 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 slice enters the INACTIVE state.
|
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.
|
protected void |
onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) |
Called back when the display orientation of a screen changes.
|
protected void |
onResult(int requestCode,
Intent resultIntent) |
Called back when the result of the
presentForResult(ohos.aafwk.ability.AbilitySlice,ohos.aafwk.content.Intent,int) method is returned. |
protected void |
onStart(Intent intent) |
Called back when an ability slice is started.
|
protected void |
onStop() |
Called back before an ability slice is destroyed.
|
void |
postTask(Runnable task,
long delayTime) |
Posts a scheduled
Runnable task to a new non-UI thread. |
void |
present(AbilitySlice targetSlice,
Intent intent) |
Presents another ability slice, which can be an ability slice that is not started or an existing ability slice
in the host ability.
|
void |
presentForResult(AbilitySlice targetSlice,
Intent intent,
int requestCode) |
Presents another ability slice and returns the result set by the target ability slice by calling
setResult(ohos.aafwk.content.Intent). |
void |
releaseAbilityForm(AbilityForm abilityForm) |
Releases a specified
AbilityForm instance of the host ability. |
boolean |
releaseForm(int formId) |
已过时。
This change is effective since API version 5. Replaced by
releaseForm(long). |
boolean |
releaseForm(long formId) |
Releases an obtained form by its ID.
|
boolean |
releaseForm(long formId,
boolean isReleaseCache) |
Releases an obtained form by its ID.
|
boolean |
requestForm(int formId) |
已过时。
This change is effective since API version 5. Replaced by
requestForm(long). |
boolean |
requestForm(long formId) |
Requests for form data update.
|
boolean |
requestForm(long formId,
Intent intent) |
已过时。
This change is effective since API version 5. Replaced by
requestForm(long). |
boolean |
reverseContinueAbility() |
Migrates the host ability from another device on the same distributed network back to the local device.
|
void |
setDisplayOrientation(AbilityInfo.DisplayOrientation requestedOrientation) |
Sets the display orientation of the host ability.
|
void |
setIsAmbientMode(boolean isEnabled) |
sets input AOD mode for window
|
void |
setLayoutParams(WindowManager.LayoutConfig params) |
Sets window layout parameters of an ability.
|
void |
setResult(Intent resultData) |
Sets the data to be returned when an ability slice is destroyed.
|
void |
setUIContent(int layoutRes) |
Inflates layout resources by using the layout resource ID.
|
void |
setUIContent(ComponentContainer componentContainer) |
Inflates UI controls by using
ComponentContainer. |
void |
startAbility(Intent intent) |
Starts a new ability.
|
void |
startAbility(Intent intent,
AbilityStartSetting abilityStartSetting) |
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.
|
boolean |
stopAbility(Intent intent) |
Destroys an ability that uses the Service template.
|
void |
terminate() |
Destroys the current ability slice.
|
void |
terminateAbility() |
Destroys the host ability.
|
String |
toString() |
Provide impl and corresponding slice info for easy human reading traces.
|
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, setPattern, setShowOnLockScreen, setTheme, setTransitionAnimation, setWakeUpScreen, startAbilities, startAbility, startAbility, startAbility, switchToCredentialEncryptedStorageContext, switchToDeviceEncryptedStorageContext, terminateAbility, terminateAbilityResult, unlockMission, verifyCallingOrSelfPermission, verifyCallingPermission, verifyPermission, verifySelfPermissionpublic static final String PARAM_FORM_CUSTOMIZE_KEY
intent.setParam(PARAM_FORM_CUSTOMIZE_KEY, intentParams).
You can put the custom data in an IntentParams object and then set this object to
the Intent used as an input parameter
of {@link #acquireForm(Intent, FormCallback).
Currently, the following data types are available for setting custom data. If an unavailable data type is used,
IllegalArgumentException is thrown.
booleanbytecharshortintlongfloatdoubleStringCharSequenceListboolean[]byte[]char[]short[]int[]long[]float[]double[]String[]CharSequence[]public static final String PARAM_FORM_DIMENSION_KEY
intent.setParam(PARAM_FORM_DIMENSION_KEY, 1).public static final String PARAM_FORM_HEIGHT_KEY
intent.setParam(PARAM_FORM_HEIGHT_KEY, 400).public static final String PARAM_FORM_IDENTITY_KEY
intent.setParam(PARAM_FORM_IDENTITY_KEY, 1L).@Deprecated public static final String PARAM_FORM_ID_KEY
PARAM_FORM_IDENTITY_KEY.intent.setParam(PARAM_FORM_ID_KEY, 1). Compatible with int form id.public static final String PARAM_FORM_NAME_KEY
intent.setParam(PARAM_FORM_NAME_KEY, "formName").public static final String PARAM_FORM_TEMPORARY_KEY
intent.setParam(PARAM_FORM_TEMPORARY_KEY, true).public static final String PARAM_FORM_WIDTH_KEY
intent.setParam(PARAM_FORM_WIDTH_KEY, 800).protected void onStart(Intent intent)
intent parameter.
You must override this method for each ability slice, and use the setUIContent(int) or
setUIContent(ohos.agp.components.ComponentContainer) method to
set the UI.
This method can be called only once in the entire lifecycle of an ability slice. Therefore, you are advised to use this method to implement initialization, for example, initializing a timer or defining a global object.
intent - Indicates information carried when the ability slice is started.protected void onActive()
The UI of an ability slice in the ACTIVE state has gained focus and is interactive.
protected void onInactive()
INACTIVE is an intermediate state and may immediately change to ACTIVE or BACKGROUND. The UI of an ability slice in this state may be visible but is not interactive. You are advised not to use this method to trigger complex service logic.
protected void onForeground(Intent intent)
The ability slice returns to the foreground. You can use this method to implement reinitialization or adjust
the UI by using the intent parameter.
intent - Indicates the information carried when the ability slice returns to the INACTIVE state.protected void onBackground()
The UI of an ability slice in the BACKGROUND state is invisible and not interactive. You are advised to use this method to stop or release resources.
protected void onStop()
This method is called back after an ability slice calls the terminate() method.
You can use this method to reclaim resources.
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 provides the same function as the Ability#onAbilityResult(int, int, Intent) method of
the ability.
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.startAbilityForResult(Intent, int)protected void onResult(int requestCode,
Intent resultIntent)
presentForResult(ohos.aafwk.ability.AbilitySlice,ohos.aafwk.content.Intent,int) method is returned.
When presentForResult(ohos.aafwk.ability.AbilitySlice,ohos.aafwk.content.Intent,int) is called to start a new ability slice, the
execution result is returned when the ability slice is destroyed.
You can override this method to process the result.
requestCode - Indicates the request code returned after the ability slice is started. You can define
the request code to identify the results returned by ability slices.
The value ranges from 0 to 65535.resultIntent - Indicates the data returned after the started ability slice is destroyed.
This parameter can be null.presentForResult(AbilitySlice, Intent, int),
setResult(Intent)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:
DisplayOrientation#LANDSCAPE, DisplayOrientation#PORTRAIT,
DisplayOrientation#FOLLOWRECENT, and DisplayOrientation#UNSPECIFIED.protected void onBackPressed()
The default implementation destroys the ability slice. You can override this method.
public boolean onKeyDown(int keyCode,
KeyEvent keyEvent)
AbilitySlice 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)
AbilitySlice 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 void postTask(Runnable task, long delayTime)
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
Ability#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.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 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.public String toString()
public Window getWindow()
This method provides the same function as the Ability#getWindow() method.
public WindowManager.LayoutConfig getLayoutParams()
This method provides the same function as the Ability#getLayoutParams() method.
null if no layout parameter is set.public void setLayoutParams(WindowManager.LayoutConfig params)
This method provides the same function as the Ability#setLayoutParams(LayoutConfig) method.
params - Indicates the WindowManager.LayoutConfig object containing
the layout parameters. This parameter cannot be null.public void setIsAmbientMode(boolean isEnabled)
isEnabled - indicates whether the AOD mode is enabledpublic 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 final void setUIContent(int layoutRes)
layoutRes - Indicates the layout resource ID, which cannot be a negative number.IllegalArgumentException - Throws this exception if layoutRes is invalid.setUIContent(ComponentContainer)public void setUIContent(ComponentContainer componentContainer)
ComponentContainer.
You can create a ComponentContainer instance that contains multiple components.
componentContainer - Indicates a set of customized components.IllegalArgumentException - Throws this exception if componentContainer is invalid.setUIContent(int)public <T extends Component> T findComponentById(int resId)
resId - Indicates the resource ID of the component.null otherwise.public final void present(AbilitySlice targetSlice, Intent intent)
You can use an Intent object to pass required information.
This method can be called only in the following cases:
targetSlice - Indicates the target ability slice, which cannot be null.intent - Indicates information carried during the switching, which cannot be null.IllegalArgumentException - Throws this exception if targetSlice is invalid.presentForResult(AbilitySlice, Intent, int)public final void presentForResult(AbilitySlice targetSlice, Intent intent, int requestCode)
setResult(ohos.aafwk.content.Intent).
You can use an Intent object to pass required information.
This method can be called only in the following cases:
targetSlice - Indicates the target ability slice. This parameter cannot be null.intent - Indicates information carried during the switching, which cannot be null.requestCode - Indicates the customized request code, which cannot be a negative number.IllegalArgumentException - Throws this exception if targetSlice or requestCode is invalid.setResult(Intent),
onResult(int, Intent)public final void setResult(Intent resultData)
When the ability slice calls the terminate() method, the result data set by the current method is
transferred to the caller.
resultData - Indicates the data returned after the ability slice is destroyed. You can define the data
returned. The value can be null.presentForResult(AbilitySlice, Intent, int),
onResult(int, Intent)public final void terminate()
When the current ability slice calls this method to destroy itself, the result data set by
setResult(ohos.aafwk.content.Intent) is returned to the caller. If the slice to be destroyed is the only slice
of its host ability, the ability will also be destroyed. Otherwise, the ability will not be affected.
public void startAbility(Intent intent)
An ability slice can also use this method to start a new ability. Similar to the function of the
Ability#startAbility(Intent) method, the system locates the target ability from installed abilities
based on the value of the intent parameter and then starts it.
intent - Indicates the ability to start.public void startAbility(Intent intent, AbilityStartSetting abilityStartSetting)
An ability slice can also use this method to start a new ability. Similar to the function of the
Ability#startAbility(Intent) method, the system locates the target ability from installed abilities
based on the value of the intent parameter and then starts it.
intent - Indicates the ability to start.abilityStartSetting - Indicates the setting ability used to start.IllegalArgumentException - Throws this exception if intent is invalid.public void startAbilityForResult(Intent intent, int requestCode, AbilityStartSetting abilityStartSetting)
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 intent is invalid.onAbilityResult(int, int, Intent)public void startAbilityForResult(Intent intent, int requestCode)
This method provides the same function as the Ability#startAbilityForResult(Intent, int) method.
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.onAbilityResult(int, int, Intent)public final AbilitySliceLifecycleExecutor.LifecycleState getState()
public final boolean stopAbility(Intent intent) throws IllegalArgumentException, IllegalStateException
This method provides the same function as the Ability#stopAbility(Intent) method.
stopAbility 在接口中 ContextstopAbility 在类中 AbilityContextintent - Indicates the ability using the Service template.true if the ability using the Service template is successfully destroyed; returns
false otherwise.IllegalArgumentException - Throws this exception if the input parameter is null.IllegalStateException - Throws this exception if the ability is not initialized.Context.stopAbility(Intent)public void terminateAbility()
This method provides the same function as the Ability#terminateAbility() method.
terminateAbility 在接口中 ContextterminateAbility 在类中 AbilityContextContext.terminateAbility()public final boolean connectAbility(Intent intent, IAbilityConnection conn) throws IllegalArgumentException, IllegalStateException
This method provides the same function as the Ability#connectAbility(Intent, IAbilityConnection)
method.
connectAbility 在接口中 ContextconnectAbility 在类中 AbilityContextintent - Indicates the ability using the Service template.conn - Indicates the transferred callback object when the ability slice is connected.true if the connection is successful; returns false otherwise.IllegalStateException - Throws this exception if the ability or ability slice is not initialized.IllegalArgumentException - Throws this exception if the input parameter is null.Context.connectAbility(Intent, IAbilityConnection)public final void disconnectAbility(IAbilityConnection conn) throws IllegalArgumentException, IllegalStateException
This method provides the same function as the Ability#disconnectAbility(IAbilityConnection) method.
disconnectAbility 在接口中 ContextdisconnectAbility 在类中 AbilityContextconn - Indicates the transferred callback object when the ability slice is connected.IllegalStateException - Throws this exception if the ability or ability slice is not initialized.IllegalArgumentException - Throws this exception if the input parameter is null.Context.disconnectAbility(IAbilityConnection)public void continueAbility()
throws IllegalStateException,
UnsupportedOperationException
This method provides the same function as the Ability#continueAbility() method.
IllegalStateException - Throws this exception if the host 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 the host ability does not implement the
IAbilityContinuation interface.public void continueAbility(String deviceId) throws IllegalStateException, UnsupportedOperationException
This method provides the same function as the Ability#continueAbility(String) method.
deviceId - Indicates the ID of the target device where the host ability will be migrated to. If this
parameter is null, this method has the same effect as continueAbility().IllegalStateException - Throws this exception if the host 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 the host ability does not implement the
IAbilityContinuation interface.public void continueAbilityReversibly()
throws IllegalStateException,
UnsupportedOperationException
reverseContinueAbility().
This method provides the same function as the Ability#continueAbilityReversibly() method.
IllegalStateException - Throws this exception if the host 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 the host ability does not implement the
IAbilityContinuation interface.public void continueAbilityReversibly(String deviceId) throws IllegalStateException, UnsupportedOperationException
reverseContinueAbility().
This method provides the same function as the Ability#continueAbilityReversibly(String) method.
deviceId - Indicates the ID of the target device where the host ability will be migrated to. If this
parameter is null, this method has the same effect as continueAbilityReversibly().IllegalStateException - Throws this exception if the host 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 the host ability does not implement the
IAbilityContinuation interface.public boolean reverseContinueAbility()
throws IllegalStateException,
UnsupportedOperationException
This method provides the same function as the Ability#reverseContinueAbility() method.
true if the migration request is successful; returns false otherwise.IllegalStateException - Throws this exception if the host 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 the host ability does not implement the
IAbilityContinuation interface.public final ContinuationState getContinuationState() throws UnsupportedOperationException
This method provides the same function as the Ability#getContinuationState() method.
UnsupportedOperationException - Throws this exception if the host ability does not implement the
IAbilityContinuation interface.public final String getOriginalDeviceId() throws UnsupportedOperationException
This method provides the same function as the Ability#getOriginalDeviceId() method.
UnsupportedOperationException - Throws this exception if the host ability does not implement the
IAbilityContinuation interface.public void setDisplayOrientation(AbilityInfo.DisplayOrientation requestedOrientation)
After you change the display orientation using this method, the system calls back the
onOrientationChanged(ohos.bundle.AbilityInfo.DisplayOrientation) method. If requestedOrientation is set to
DisplayOrientation#UNSPECIFIED, the display orientation of the ability depends on the system setting.
If an ability is in the foreground, the setting takes effect immediately. Otherwise, the setting takes effect when the ability returns to the foreground.
setDisplayOrientation 在接口中 ContextsetDisplayOrientation 在类中 AbilityContextrequestedOrientation - Indicates the display orientation, which can be UNSPECIFIED,
LANDSCAPE, PORTRAIT, or FOLLOWRECENT.IllegalArgumentException - Throws this exception if requestedOrientation is invalid.Context.setDisplayOrientation(AbilityInfo.DisplayOrientation)public boolean acquireAbilityFormAsync(Intent intent, AbilityForm.OnAcquiredCallback acquiredCallback)
AbilityForm instance provided by the target ability.
This method is executed asynchronously. After the AbilityForm instance is obtained, the system calls
back the OnAcquiredCallback method. If the target ability does not use the Page template
or does not provide the AbilityForm capability, the caller is not notified.
To use this method, your application must have the ohos.permission.REQUIRE_FORM permission. This
permission is available only to system applications. If the caller does not have the permission, false is
returned.
intent - Indicates the target ability.acquiredCallback - Indicates the notification callback after the AbilityForm instance is
asynchronously obtained.true if the request is sent successfully; returns false otherwise.IllegalArgumentException - Throws this exception if intent or acquiredCallback is invalid.public boolean acquireForm(Intent intent, AbilitySlice.FormCallback callback) throws FormException
Intent.
This method is asynchronous. After the Form instance is obtained,
AbilitySlice.FormCallback.onAcquired(int, Form) will be
invoked to notify the application.
Permissions: SystemPermission.REQUIRE_FORM;
SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
intent - Indicates the detailed information about the form to be obtained, including the bundle name,
module name, ability name, form name, form grid styles, form width and height, and form ID.callback - Indicates the callback to be invoked whenever the Form instance is obtained.true if the request is successfully initiated; returns false otherwise.FormException - Throws this exception if the form fails to be obtained due to any of the following reasons:
Intent does not bear the necessary bundleName, abilityName,
and moduleName.SystemPermission.REQUIRE_FORM or
SystemPermission.GET_BUNDLE_INFO_PRIVILEGED permission.@Deprecated public boolean deleteForm(int formId) throws FormException
deleteForm(long).After this method is called, the form won't be available for use by the application and the Form Manager Service no longer keeps the cache information about the form.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the form ID, which can be obtained via Form.getId().true if the form is successfully deleted; returns false otherwise.FormException - Throws this exception if the form fails to be deleted due to any of the following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.public boolean deleteForm(long formId)
throws FormException
After this method is called, the form won't be available for use by the application and the Form Manager Service no longer keeps the cache information about the form.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the form ID, which can be obtained via Form.getId().true if the form is successfully deleted; returns false otherwise.FormException - Throws this exception if the form fails to be deleted due to any of the following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.@Deprecated public boolean releaseForm(int formId) throws FormException
releaseForm(long).After this method is called, the form won't be available for use by the application, but the Form Manager
Service still keeps the cache information about the form, so that the application can quickly obtain it based on
the formId.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the form ID, which can be obtained via Form.getFormId().true if the form is successfully released; returns false otherwise.FormException - Throws this exception if the form fails to be released due to any of the following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.public boolean releaseForm(long formId)
throws FormException
After this method is called, the form won't be available for use by the application, but the Form Manager
Service still keeps the cache information about the form, so that the application can quickly obtain it based on
the formId.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the form ID, which can be obtained via Form.getId().true if the form is successfully released; returns false otherwise.FormException - Throws this exception if the form fails to be released due to any of the following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.public boolean releaseForm(long formId,
boolean isReleaseCache)
throws FormException
After this method is called, the form won't be available for use by the application, if isReleaseCache is
false, this method is same as releaseForm(int), otherwise the Form Manager Service still store this
form in the cache.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the form ID, which can be obtained via Form.getId().isReleaseCache - Indicates whether to clear cache in service.true if the form is successfully released; returns false otherwise.FormException - Throws this exception if the form fails to be released due to any of the following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.public boolean castTempForm(long formId)
throws FormException
After this method is successfully called, the temporary form will be converted to a normal form, the data in the cache will be updated accordingly, and the form data such as the form ID will be made persistent.
Permissions: SystemPermission.REQUIRE_FORM
formId - Indicates the ID of the temporary form to convert, which is obtained via
Form.getId().true if the conversion is successful; returns false otherwise.FormException - Throws this exception if the form fails to be converted due to any of the
following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.Form instances in the cache of the Form Manager Service has reached the upper limit
(512). public void notifyVisibleForms(List<Long> formIds) throws FormException
After this method is successfully called, Ability.onEventNotify(Map<Long, int>)
will be called to notify the form provider of the form visibility change event.
Permissions: SystemPermission.REQUIRE_FORM
formIds - Indicates the IDs of the forms to be made visible.FormException - Throws this exception if the forms fail to be made visible
due to any of the following reasons:
formIds parameter is invalid. Each form ID in it must be larger than 0.SystemPermission.REQUIRE_FORM permission.public void notifyInvisibleForms(List<Long> formIds) throws FormException
After this method is successfully called, Ability.onEventNotify(Map<Long, int>)
will be called to notify the form provider of the form visibility change event.
Permissions: SystemPermission.REQUIRE_FORM
formIds - Indicates the IDs of the forms to be made invisible.FormException - Throws this exception if the forms fail to be made invisible
due to any of the following reasons:
formIds parameter is invalid. Each form ID in it must be larger than 0.SystemPermission.REQUIRE_FORM permission.public int checkAndDeleteInvalidForms(List<Long> persistedIds) throws FormException
If an empty list is passed to this method, the Form Manager Service will delete all forms of the application.
Permissions: SystemPermission.REQUIRE_FORM
persistedIds - Indicates the list of valid forms with persisted IDs.FormException - Throws this exception if the invalid forms fail to be deleted due to any of the
following reasons:
persistedIds is invalid. The value of persistedIds must not be null.persistedIds has reached the upper limit (256) allowed for
a single application.SystemPermission.REQUIRE_FORM permission.public void acquireFormState(Intent intent, AbilitySlice.FormCallback callback) throws FormException
intent.
This method is asynchronous. After the FormState is obtained,
AbilitySlice.FormCallback.onAcquiredState(Intent, FormState) will be invoked to
notify the application.
Permissions: SystemPermission.REQUIRE_FORM;
SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
intent - Indicates the detailed information of the form to be obtained, including the bundle name,
ability name, module name, form name, and form grid style.callback - Indicates the callback to be invoked whenever the FormState is obtained.FormException - Throws this exception if the form state fails to be obtained due to any of
the following reasons:
intent does not bear the necessary bundleName, abilityName,
moduleName, formName, and dimension.SystemPermission.REQUIRE_FORM or
SystemPermission.GET_BUNDLE_INFO_PRIVILEGED permission.public List<FormInfo> getAllFormsInfo() throws FormException
FormInfo objects provided by all applications on the device.
Permission: SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
FormInfo objects if obtained; returns an empty List if no
FormInfo is available on the device.FormException - Throws this exception if FormInfo fails to be obtained due to a connection error
between the application and bundle manager service or because the application is not
granted with the SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
permission.@Deprecated public List<FormInfo> getAllForms() throws FormException
getAllFormsInfo().FormInfo objects provided by all applications on the device.
Permission: SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
FormInfo objects if obtained; returns an empty List if no
FormInfo is available on the device.FormException - Throws this exception if FormInfo fails to be obtained due to a connection error
between the application and bundle manager service or because the application is not
granted with the SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
permission.public List<FormInfo> getFormsInfoByApp(String bundleName) throws FormException
FormInfo objects provided by a specified application on the device.
Permission: SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
bundleName - Indicates the bundle name of the application. Specifically, it is the value of the
bundleName attribute defined in the app tag of the config.json file for
the application.FormInfo objects if obtained; returns an empty List if no
FormInfo is provided by the specified application.FormException - Throws this exception if FormInfo fails to be obtained due to a connection error
between the application and bundle manager service or because the application is not
granted with the SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
permission.@Deprecated public List<FormInfo> getFormsByApp(String bundleName) throws FormException
getFormsInfoByApp(java.lang.String).FormInfo objects provided by a specified application on the device.
Permission: SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
bundleName - Indicates the bundle name of the application. Specifically, it is the value of the
bundleName attribute defined in the app tag of the config.json file for
the application.FormInfo objects if obtained; returns an empty List if no
FormInfo is provided by the specified application.FormException - Throws this exception if FormInfo fails to be obtained due to a connection error
between the application and bundle manager service or because the application is not
granted with the SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
permission.public List<FormInfo> getFormsInfoByModule(String bundleName, String moduleName) throws FormException
FormInfo objects provided by a specified application module on the device.
Permission: SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
bundleName - Indicates the bundle name of the application. Specifically, it is the value of the
bundleName attribute defined in the app tag of the config.json file for
the application.moduleName - Indicates the module name of the application. Specifically, it is the value of the
moduleName sub-attribute of the distro attribute defined in the module
tag of the config.json file for the application.FormInfo objects if obtained; returns an empty List if no
FormInfo is provided by the specified application module.FormException - Throws this exception if FormInfo fails to be obtained due to a connection error
between the application and bundle manager service or because the application is not
granted with the SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
permission.@Deprecated public List<FormInfo> getFormsByModule(String bundleName, String moduleName) throws FormException
getFormsInfoByModule(java.lang.String,java.lang.String).FormInfo objects provided by a specified application module on the device.
Permission: SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
bundleName - Indicates the bundle name of the application. Specifically, it is the value of the
bundleName attribute defined in the app tag of the config.json file for
the application.moduleName - Indicates the module name of the application. Specifically, it is the value of the
moduleName sub-attribute of the distro attribute defined in the module
tag of the config.json file for the application.FormInfo objects if obtained; returns an empty List if no
FormInfo is provided by the specified application module.FormException - Throws this exception if FormInfo fails to be obtained due to a connection error
between the application and bundle manager service or because the application is not
granted with the SystemPermission.GET_BUNDLE_INFO_PRIVILEGED
permission.@Deprecated public boolean requestForm(int formId) throws FormException
requestForm(long).This method must be called when the application has detected that a system setting item (such as the language, resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form provider automatically updates the form data (if there is any update) through the form framework, with the update process being unperceivable by the application.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the ID of the form to update.true if the update request is successfully initiated; returns false otherwise.FormException - Throws this exception if the update request fails to be initiated due to any of the
following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.public boolean requestForm(long formId)
throws FormException
This method must be called when the application has detected that a system setting item (such as the language, resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form provider automatically updates the form data (if there is any update) through the form framework, with the update process being unperceivable by the application.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the ID of the form to update.true if the update request is successfully initiated; returns false otherwise.FormException - Throws this exception if the update request fails to be initiated due to any of the
following reasons:
formId is invalid. Its value must be larger than 0.SystemPermission.REQUIRE_FORM permission.@Deprecated public boolean requestForm(long formId, Intent intent) throws FormException
requestForm(long).intent) to the form provider.
This method must be called when the application has detected that a system setting item (such as the language, resolution, or screen orientation) being listened for has changed. Upon receiving the update request, the form provider automatically updates the form data (if there is any update) through the form framework, with the update process being unperceivable by the application.
Permission: SystemPermission.REQUIRE_FORM
formId - Indicates the ID of the form to update.intent - Indicates a set of parameters to be transparently passed to the form provider.true if the update request is successfully initiated; returns false otherwise.FormException - Throws this exception if the update request fails to be initiated due to any of the
following reasons:
formId or intent is invalid. The value of formId must be larger than 0,
and intent must not be null.SystemPermission.REQUIRE_FORM permission.public void releaseAbilityForm(AbilityForm abilityForm)
AbilityForm instance of the host ability.abilityForm - Indicates the AbilityForm instances to release.IllegalArgumentException - Throws this exception if abilityForm is invalid or
the IAbilityConnection object related to the abilityForm cannot be obtained.public final Lifecycle getLifecycle()
Lifecycle object of the current ability slice.getLifecycle 在接口中 ILifecycleLifecycle object.