Skip to content

Instantly share code, notes, and snippets.

@kairos34
Created May 25, 2022 09:38
Show Gist options
  • Save kairos34/b99692f404fb33ff69ddbe57e3eafdd9 to your computer and use it in GitHub Desktop.
Save kairos34/b99692f404fb33ff69ddbe57e3eafdd9 to your computer and use it in GitHub Desktop.
Enable NFC feature if device has it
fun turnOnNfc() {
runBlocking {
var count = 0
NfcAdapter.getDefaultAdapter(get())?.run {
enableNfc()
while (!isEnabled) {
Log.i("TAG", "Waiting for NFC adapter to turn on")
delay(200)
count += 1
if(count > 10) {
Log.w("TAG", "No NFC adapter found after $count attempts")
return@runBlocking
}
}
Log.i("TAG", "NFC adapter turned on")
} ?: run {
Log.i("TAG", "No NFC adapter found, skipping turning NFC on")
}
}
}
fun enableNfc() {
nfcServiceCall(
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> 8
else -> 7
})
}
fun disableNfc() {
nfcServiceCall(
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> 7
else -> 6
})
}
private fun nfcServiceCall(value: Int) {
GlobalScope.launch {
"service call nfc $value".runCommand()
}
}
fun String.runCommand() = run {
execCommands(this)
}
@Throws(IOException::class)
fun execCommands(vararg commands: String): Int {
var result = 1
val runTime = Runtime.getRuntime()
val process = runTime.exec("su")
val os = DataOutputStream(
process.outputStream
)
try {
for (element in commands) {
os.writeBytes(
"""
$element
""".trimIndent()
)
os.flush()
}
os.writeBytes("exit\n")
os.flush()
process.waitFor()
result = process.exitValue()
} catch (e: InterruptedException) {
return result
} finally {
os.close()
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment