本文原创发布在华为开发者社区。
介绍
本示例介绍了应用跳转的多个场景案例。
- 跳转短信、浏览器、设置、相机、拨号、应用市场等系统应用和已知bundlename、abilityname的三方应用。
- 跳转相机拍照后返回照片展示。
- 跳转三方应用,模拟简易支付。
- 跳转web页,拉起相机和三方应用。
效果预览
使用说明
打开应用,展示一列按钮,点击不同按钮会进行不同应用的跳转。有些跳转需要权限,每次跳转前会弹窗提示。
实现思路
点击跳转系统相机应用
- 构造startAbility()函数,用于启动一个特定的能力(ability)。构建一个Want对象,包含要执行的操作(action)和参数(parameters),其中参数包括调用应用的Bundle名称(callBundleName)和是否支持多模式(supportMultiMode)。尝试使用this.context.startAbilityForResult启动能力,并在回调中处理结果。如果启动过程中出现错误(err.code 存在),记录错误日志并返回。如果启动成功,从结果中获取资源URI(uri),记录成功日志,并根据uri是否存在执行不同操作:若uri存在,调用this.save2Local方法保存到本地;若uri不存在,显示 “拍摄失败” 的提示。
startAbility(action: string, bundleName: string) {
let want: Want = {
action: action,
parameters: {
// 拍照完成后返回的应用BundleName
callBundleName: bundleName,
supportMultiMode: false
}
};
try {
this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
if (err.code) {
// 处理业务逻辑错误
hilog.error(0x0000, 'startAbilityForResult failed', `${err.code}${err.message}`);
return;
}
let uri: string = result?.want?.parameters?.resourceUri as string;
// 执行正常业务
hilog.info(0x0000, 'Succeeded in starting ability for result', `${JSON.stringify(result)}${uri}`);
if (uri) {
// 保存到本地
this.save2Local(uri);
} else {
promptAction.showToast({ message: '拍摄失败' })
}
});
}
}
- 构造save2Local()函数,将通过uri标识的文件保存到本地沙箱目录。
save2Local(uri: string) {
try {
let file = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY);
let prefix = uri.substring(uri.lastIndexOf('.') + 1);
let tempFileName = getContext(this).filesDir + '/' + new Date().getTime() + '.' + prefix;
let tempFile = fileIo.openSync(tempFileName, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
fileIo.copyFileSync(file.fd, tempFile.fd);
this.path = fileUri.getUriFromPath(tempFileName);
this.isVideo = (prefix == 'mp4' || prefix == 'MP4');
hilog.info(0x0000, 'resolve2Sandbox successful.', '');
promptAction.showToast({ message: '拍摄成功' })
}
}
点击跳转Web应用
构造jumpTestApp()函数,启动一个特定的应用(通过bundleName和abilityName指定),并向其传递参数(parameters中的 message)。该函数返回一个Promise,在启动应用成功并获取到结果后,解析并返回结果中的 result 值;如果启动过程中出现错误,记录错误日志并返回 'failed'。
async jumpTestApp(): Promise<string> {
let wantInfo: Want = {
deviceId: '',
bundleName: 'com.example.test1',
abilityName: 'EntryAbility',
parameters: {
message: '待支付¥100'
}
}
return this.context.startAbilityForResult(wantInfo).then((abilityResult) => {
return abilityResult.want!.parameters!.result.toString();
})
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。