I have an issue with this code where the return packageSize
statement is triggered before the onGetStatsCompleted
function and it returns 0 instead of the right value. Is there a way I can force onGetStatsCompleted
to finish before returning packageSize
? I know it's a logic issue because if I remove the comment at //Thread.sleep
it works fine.
How do I fix this without using Thread.sleep
or any other kind of time out in the application?
private var packageSize: Long = 0
private var dataSize: Long = 0
private var cacheSize: Long = 0
private var apkSize: Long = 0
/**
Get the size of the app for API < 26
*/
@Throws(InterruptedException::class)
fun getPackageSize(): Long {
val pm = context.packageManager
try {
val getPackageSizeInfo = pm.javaClass.getMethod(
"getPackageSizeInfo", String::class.java, IPackageStatsObserver::class.java)
getPackageSizeInfo.invoke(pm, context.packageName,
object : CachePackState() {//Call inner class
})
} catch (e: Exception) {
e.printStackTrace()
}
//Thread.sleep(1000)
return packageSize
}
/**
Inner class which will get the data size for the application
*/
open inner class CachePackState : IPackageStatsObserver.Stub() {
override fun onGetStatsCompleted(pStats: PackageStats, succeeded: Boolean) {
//here the pStats has all the details of the package
dataSize = pStats.dataSize
cacheSize = pStats.cacheSize
apkSize = pStats.codeSize
packageSize = cacheSize + apkSize
}
}
Feel free to ask any questions, any help is appreciated.
from How do I wait for a function to be done executing before returning a value?
No comments:
Post a Comment