在鸿蒙(HarmonyOS)中安装 .app 格式的应用包(即 HAP 或 APP 文件),可以通过以下方法实现
1. 通过 hmos
命令行工具安装(开发者常用)
适用于开发调试阶段,使用 hdc
(HarmonyOS Device Connector)工具安装。
步骤:
-
连接设备
确保设备已通过USB或网络连接,并开启开发者模式。sh
hdc shell
-
推送
.app
文件到设备sh
hdc file send yourapp.app /data/local/tmp/
-
安装应用
sh
hdc shell bm install -p /data/local/tmp/yourapp.app
-
-p
:指定安装包路径。 -
-r
:覆盖安装(可选)。
-
-
查看已安装应用
sh
hdc shell bm list
2. 通过 BundleManager
API 安装(代码方式)
适用于应用内静默安装(需系统权限)。
示例代码
java
import ohos.bundle.BundleManager;
import ohos.bundle.IBundleInstaller;
import ohos.rpc.RemoteException;// 1. 获取 BundleManager
BundleManager bundleManager = getContext().getBundleManager();// 2. 获取 BundleInstaller
IBundleInstaller installer = bundleManager.getBundleInstaller();// 3. 构造安装参数
String hapPath = "/data/local/tmp/yourapp.app"; // .app 文件路径
List<String> hapPaths = new ArrayList<>();
hapPaths.add(hapPath);// 4. 执行安装
try {installer.install(hapPaths, new BundleInstallerCallback() {@Overridepublic void onFinished(int resultCode, String resultMsg) {if (resultCode == IBundleInstaller.SUCCESS) {System.out.println("安装成功");} else {System.out.println("安装失败: " + resultMsg);}}});
} catch (RemoteException e) {e.printStackTrace();
}
注意事项
-
需要系统权限:普通应用无法直接调用
BundleInstaller
,需系统级应用或签名权限。 -
仅限调试:正式发布的应用应通过应用市场安装。
3. 通过 Intent
调用系统安装界面(用户手动安装)
适用于用户主动安装 .app
文件(如从文件管理器打开)。
示例代码
java
Intent intent = new Intent();
Operation operation = new Intent.OperationBuilder().withAction(Intent.ACTION_VIEW).withUri("file:///storage/emulated/0/Download/yourapp.app") // .app 文件路径.withFlags(Intent.FLAG_ABILITY_NEW_MISSION).build();
intent.setOperation(operation);
startAbility(intent);
配置 config.json
(目标设备需支持)
json
"abilities": [{"name": "InstallAbility","type": "page","skills": [{"actions": ["Intent.ACTION_VIEW"],"uris": [{"scheme": "file","type": "application/vnd.hap"}]}]}
]
4. 通过 AppGallery
(华为应用市场)安装
正式发布的鸿蒙应用应上传至 AppGallery,用户通过应用市场安装。
常见问题
Q1:.app
文件是什么?
-
.app
是鸿蒙的应用包格式,可以是:-
HAP(Harmony Ability Package):单个功能模块。
-
APP(多HAP集合):完整的应用包。
-
Q2:安装失败怎么办?
-
检查签名:调试包需使用调试证书,正式包需企业/开发者证书。
-
存储权限:确保应用有读取
.app
文件的权限。 -
兼容性:设备系统版本需支持目标API。
总结
方法 | 适用场景 | 是否需要权限 |
---|---|---|
hdc 命令行 | 开发者调试 | 需设备连接 |
BundleInstaller | 系统级静默安装 | 需系统权限 |
Intent 调用安装界面 | 用户手动安装 | 需文件权限 |
AppGallery | 正式发布 | 无需额外权限 |
如果是普通应用分发,建议使用 AppGallery;调试阶段可使用 hdc
或 Intent
方式安装。