Issue
Background
Using root, I know that for a single APK file, we can use the "libsu" library (here) to install as such:
val installResult = Shell.su("pm install -t \"$filePath\"").exec()
And if that failed (fails on new Android versions, not sure from which), as such (written about this here):
val installResult = Shell.su("cat \"$filePath\" | pm install -t -S ${apkSource.fileSize}").exec()
I also know that things got quite messy when it comes to installing split APK files (as shown here). First you need to create a session, using the "pm install-create" command:
var sessionId: Int? = null
run {
val sessionIdResult =
Shell.su("pm install-create -r -t").exec().out
val sessionIdPattern = Pattern.compile("(\\d+)")
val sessionIdMatcher = sessionIdPattern.matcher(sessionIdResult[0])
sessionIdMatcher.find()
sessionId = Integer.parseInt(sessionIdMatcher.group(1)!!)
Log.d("AppLog", "sessionId:$sessionId")
}
Then you have to "push" each of the APK files, as such:
for (apkSource in fileInfoList) {
val filePath = File(apkSource.parentFilePath, apkSource.fileName).absolutePath
Log.d("AppLog", "installing APK : $filePath ${apkSource.fileSize} ")
val result = Shell.su("pm install-write -S ${apkSource.fileSize} $sessionId \"${apkSource.fileName}\" \"$filePath\"").exec()
Log.d("AppLog", "success pushing apk:${apkSource.fileName} ? ${result.isSuccess}")
}
And then you commit the changes using pm install-commit
:
val installResult = Shell.su("pm install-commit $sessionId").exec()
Docs about it all:
install-create [-lrtsfdg] [-i PACKAGE] [--user USER_ID|all|current]
[-p INHERIT_PACKAGE] [--install-location 0/1/2]
[--install-reason 0/1/2/3/4] [--originating-uri URI]
[--referrer URI] [--abi ABI_NAME] [--force-sdk]
[--preload] [--instantapp] [--full] [--dont-kill]
[--force-uuid internal|UUID] [--pkg PACKAGE] [--apex] [-S BYTES]
[--multi-package] [--staged]
Like "install", but starts an install session. Use "install-write"
to push data into the session, and "install-commit" to finish.
install-write [-S BYTES] SESSION_ID SPLIT_NAME [PATH|-]
Write an apk into the given install session. If the path is '-', data
will be read from stdin. Options are:
-S: size in bytes of package, required for stdin
install-commit SESSION_ID
Commit the given active install session, installing the app.
The problem
This all worked fine till Android P, but for some reason, it failed on Q beta 6, showing me this error:
avc: denied { read } for scontext=u:r:system_server:s0 tcontext=u:object_r:sdcardfs:s0 tclass=file permissive=0
System server has no access to read file context u:object_r:sdcardfs:s0 (from path /storage/emulated/0/Download/split/base.apk, context u:r:system_server:s0)
Error: Unable to open file: /storage/emulated/0/Download/split/base.apk
Consider using a file under /data/local/tmp/
What I've tried
This is similar to the case I've found for the single APK , here, so I thought that maybe a similar solution can be applied here too:
val result = Shell.su("cat $filePath | pm install-write -S ${apkSource.fileSize} $sessionId \"${apkSource.fileName}\" \"$filePath\"").exec()
This still worked only on Android P and below.
So seeing that the original code I looked at worked, it uses an InputStream, which as the docs imply, is possible. Here's what they had:
while (apkSource.nextApk())
ensureCommandSucceeded(Root.exec(String.format("pm install-write -S %d %d \"%s\"", apkSource.getApkLength(), sessionId, apkSource.getApkName()), apkSource.openApkInputStream()));
So what I tried is as such:
val result = Shell.su("pm install-write -S ${apkSource.fileSize} $sessionId \"${apkSource.fileName}\" -")
.add(SuFileInputStream(filePath)).exec()
Sadly this also didn't work.
The question
I know I could just copy the same code, but is there still a way to use the library instead (because it will be shorter and more elegant)? If so, how could I do it?
Solution
OK I don't know how to use this library to install the split-apk, but here's a short code that seems to work using a different library :
build.gradle
//https://github.com/topjohnwu/libsu
implementation "com.github.topjohnwu.libsu:core:2.5.1"
Base class of a single/split apk file :
open class FileInfo(val name: String, val fileSize: Long, val file: File? = null) {
open fun getInputStream(): InputStream = if (file!= null) FileInputStream(file) else throw NotImplementedError("need some way to create InputStream")
}
getting root and installing:
Shell.getShell {
val isRoot = it.isRoot
Log.d("AppLog", "isRoot ?$isRoot ")
AsyncTask.execute {
val apkFilesPath = "/storage/emulated/0/Download/split/"
val fileInfoList = getFileInfoList(apkFilesPath)
installSplitApkFiles(fileInfoList)
}
}
The installation itself:
@WorkerThread
private fun installSplitApkFiles(apkFiles: ArrayList<FileInfo>): Boolean {
if (apkFiles.size == 1) {
//single file that we can actually reach, so use normal method
val apkFile = apkFiles[0]
if (apkFiles[0].apkFile != null) {
Log.d("AppLog", "Installing a single APK ${apkFile.name} ${apkFile.fileSize} ")
val installResult = Shell.su("cat \"${apkFile.apkFile!!.absolutePath}\" | pm install -t -S ${apkFile.fileSize}").exec()
Log.d("AppLog", "succeeded installing?${installResult.isSuccess}")
if (installResult.isSuccess)
return true
}
}
var sessionId: Int? = null
Log.d("AppLog", "installing split apk files:$apkFiles")
run {
val sessionIdResult = Shell.su("pm install-create -r -t").exec().out
// Note: might need to use these instead:
// "pm install-create -r --install-location 0 -i '${BuildConfig.APPLICATION_ID}'"
// "pm install-create -r -i '${BuildConfig.APPLICATION_ID}'"
val sessionIdPattern = Pattern.compile("(\\d+)")
val sessionIdMatcher = sessionIdPattern.matcher(sessionIdResult[0])
sessionIdMatcher.find()
sessionId = Integer.parseInt(sessionIdMatcher.group(1)!!)
// Log.d("AppLog", "sessionId:$sessionId")
}
for (apkFile in apkFiles) {
Log.d("AppLog", "installing APK : ${apkFile.name} ${apkFile.fileSize} ")
// pm install-write [-S BYTES] SESSION_ID SPLIT_NAME [PATH]
val command = arrayOf("su", "-c", "pm", "install-write", "-S", "${apkFile.fileSize}", "$sessionId", apkFile.name)
val process: Process = Runtime.getRuntime().exec(command)
val inputPipe = apkFile.getInputStream()
try {
process.outputStream.use { outputStream -> inputPipe.copyTo(outputStream) }
} catch (e: java.lang.Exception) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) process.destroyForcibly() else process.destroy()
throw RuntimeException(e)
}
process.waitFor()
val inputStr = process.inputStream.readBytes().toString(Charset.defaultCharset())
val errStr = process.errorStream.readBytes().toString(Charset.defaultCharset())
val isSucceeded = process.exitValue() == 0
Log.d("AppLog", "isSucceeded?$isSucceeded inputStr:$inputStr errStr:$errStr")
}
// "pm install-commit %d ", sessionId
Log.d("AppLog", "committing...")
val installResult = Shell.su("pm install-commit $sessionId").exec()
Log.d("AppLog", "succeeded installing?${installResult.isSuccess}")
return installResult.isSuccess
}
getting a list of split apk files as an example:
fun SimpleDateFormat.tryParse(str: String) = try {
parse(str) != null
} catch (e: Exception) {
false
}
@WorkerThread
private fun getFileInfoList(splitApkPath: String): ArrayList<FileInfo> {
val parentFile = File(splitApkPath)
val result = ArrayList<FileInfo>()
if (parentFile.exists() && parentFile.canRead()) {
val listFiles = parentFile.listFiles() ?: return ArrayList()
for (file in listFiles)
result.add(FileInfo(file.name, file.length(), file))
return result
}
val longLines = Shell.su("ls -l $splitApkPath").exec().out
val pattern = Pattern.compile(" +")
val formatter = SimpleDateFormat("HH:mm", Locale.getDefault())
longLinesLoop@ for (line in longLines) {
// Log.d("AppLog", "line:$line")
val matcher = pattern.matcher(line)
for (i in 0 until 4)
if (!matcher.find())
continue@longLinesLoop
//got to file size
val startSizeStr = matcher.end()
matcher.find()
val endSizeStr = matcher.start()
val fileSizeStr = line.substring(startSizeStr, endSizeStr)
while (true) {
val testTimeStr: String =
line.substring(matcher.end(), line.indexOf(' ', matcher.end()))
if (formatter.tryParse(testTimeStr)) {
//found time, so apk is next
val fileName = line.substring(line.indexOf(' ', matcher.end()) + 1)
if (fileName.endsWith("apk"))
// Log.d("AppLog", "fileSize:$fileSizeStr fileName:$fileName")
result.add(FileInfo(fileName, fileSizeStr.toLong(), File(splitApkPath, fileName)))
break
}
matcher.find()
}
}
// Log.d("AppLog", "result:${result.size}")
return result
}
Answered By - android developer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.