index.uts 1.4 KB
Newer Older
1 2
import { InstallApkOptions, InstallApkSuccess } from "../interface.uts"
import { InstallApkFailImpl } from "../unierror.uts"
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
3 4 5 6 7 8 9 10 11 12 13 14
import Intent from 'android.content.Intent';
import Build from 'android.os.Build';
import File from 'java.io.File';
import FileProvider from 'androidx.core.content.FileProvider';
import Context from 'android.content.Context';
import Uri from 'android.net.Uri';

export function installApk(options : InstallApkOptions) : void {
	const context = UTSAndroid.getAppContext() as Context
	const filePath = UTSAndroid.convert2AbsFullPath(options.filePath)
	const apkFile = new File(filePath)
	if (!apkFile.exists() && !apkFile.isFile()) {
15
		let error = new InstallApkFailImpl(1300002);
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
		options.fail?.(error)
		options.complete?.(error)
		return
	}
	const intent = new Intent()
	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
	intent.setAction(Intent.ACTION_VIEW)

	if (Build.VERSION.SDK_INT >= 24) {
		const authority = context.getPackageName() + ".dc.fileprovider"
		const apkUri = FileProvider.getUriForFile(context, authority, apkFile)
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
	} else {
		intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
	}
		
	context.startActivity(intent)
	const success : InstallApkSuccess = {
		errMsg: "success"
	}
	options.success?.(success)
	options.complete?.(success)
}