Skip to content

Instantly share code, notes, and snippets.

@dave08
Created May 1, 2018 18:15
Show Gist options
  • Save dave08/f8d6a717f25b426e00fcfabc73b7197d to your computer and use it in GitHub Desktop.
Save dave08/f8d6a717f25b426e00fcfabc73b7197d to your computer and use it in GitHub Desktop.
import android.content.Context
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.TedPermission
import kotlinx.coroutines.experimental.CoroutineStart
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.suspendCancellableCoroutine
import timber.log.Timber
import java.util.ArrayList
fun <T> Context.withPermission(permission: String, block: () -> T) = async(start = CoroutineStart.LAZY) {
return@async if (checkForPermission(permission)) block() else null
}
suspend fun Context.checkForPermission(permission: String): Boolean =
suspendCancellableCoroutine {
try {
TedPermission.with(this)
.setPermissionListener(object : PermissionListener {
override fun onPermissionGranted() {
it.resume(true)
}
override fun onPermissionDenied(deniedPermissions: ArrayList<String>?) {
if (deniedPermissions?.contains(permission) != null)
it.resume(false)
else
it.resume(true)
}
})
.setPermissions(permission)
.check()
}
catch (e: Exception){
Timber.e(e, "check permission failed")
}
}
// Usage:
context.withPermission(Manifest.permission.READ_PHONE_STATE) {
(context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).simSerialNumber
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment