Created
June 6, 2018 12:11
-
-
Save mnaraniya/bac5e4c7d8cd7a4473b288916ee81fd8 to your computer and use it in GitHub Desktop.
Use this to use Android Runtime Permission simply in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mukesh.call.runtimepermission | |
//imports below | |
class MainActivity : AppCompatActivity() { | |
private val REQUEST_CODE_ASK_PERMISSIONS = 123 | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
permissionProcess() | |
} | |
fun myMethod(){ | |
// your main stuff | |
} | |
fun permissionProcess(v: View) { | |
if (Build.VERSION.SDK_INT < 23) { | |
// do your stuff | |
myMethod() | |
} else { | |
val hasReadContactsPermission = checkSelfPermission(Manifest.permission.READ_CALL_LOG) | |
if (hasReadContactsPermission != PackageManager.PERMISSION_GRANTED) { | |
requestPermissions(arrayOf(Manifest.permission.READ_CALL_LOG), | |
REQUEST_CODE_ASK_PERMISSIONS) | |
return | |
} | |
// do your stuff | |
myMethod() | |
} | |
} | |
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { | |
when (requestCode) { | |
REQUEST_CODE_ASK_PERMISSIONS -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { | |
// Permission Granted, do your stuff | |
myMethod() | |
} else { | |
// Permission Denied | |
Toast.makeText(this@MainActivity, "READ_CALL_LOG Denied", Toast.LENGTH_SHORT) | |
.show() | |
} | |
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment