Usefull Android Posts

Create Foreground Service

https://robertohuertas.com/2019/06/29/android_foreground_services/

Check that application is installed

object PackageUtils {
    fun isAppInstalled(context: Context, packageName: String?): Boolean {
        val packageManager = context.packageManager
        return try {
            packageManager.getPackageInfo(packageName!!, PackageManager.GET_ACTIVITIES)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }
}

Check that application is running

object ProcessUtils {

    private const val TAG = "ProcessUtils"
    data class CommandResponse(
        val status: Int,
        val stdOut: String,
        val stdErr: String
    )
    fun runCommand(args: Array<String>): CommandResponse {
        Log.i(TAG, "Running command $${args.joinToString(" ")}")
        val pb = ProcessBuilder(args.toMutableList())
        val process = pb.start()
        return CommandResponse(process.waitFor(), process.inputStream.readBytes().decodeToString(), process.errorStream.readBytes().decodeToString())
    }

    fun isAppRunning(context: Context, packageName: String): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val processInfos = activityManager.runningAppProcesses
        for (processInfo in processInfos) {
            if (processInfo.processName == packageName) {
                return true
            }
        }
        return false
    }
    
}

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *