我写了权限类,这里有 askMicrophonePermission
方法。
在 askMicrophonePermission 中,我使用 ActivityCompat.requestPermissions
功能。
但我无法在中覆盖 onRequestPermissionsResult 权限
类。
如果我想在权限中覆盖 onRequestPermissionsResult ,则不
在 MainActivity 中。
怎么写??这是我的代码。
主要 Activity :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Permission().askMicrophonePermission(this@MainActivity)
}
}
允许:
class Permission{
private val tag = "Permission message"
private val userMicrophonePermissionAgreeCode = 1
fun askMicrophonePermission(context: Context){
val currentMicrophonePermission = ActivityCompat.checkSelfPermission(context,android.Manifest.permission.RECORD_AUDIO)
if(currentMicrophonePermission != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(context as Activity, arrayOf(android.Manifest.permission.RECORD_AUDIO), userMicrophonePermissionAgreeCode)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode){
userMicrophonePermissionAgreeCode -> {
if( grantResults[0] == PackageManager.PERMISSION_GRANTED )
Log.i(tag,"Agree microphone permission")
else
Log.i(tag,"Not agree microphone permission")
}
}
}
}
最佳答案
onRequestPermissionsResult
是FragmentActivity
中的一种方法。由于Permission
不会扩展FragmentActivity
,因此您不能直接在onRequestPermissionsResult
中覆盖Permission
。
您可以将权限结果委托(delegate)给Permission
。
class MainActivity : AppCompatActivity() {
private lateinit var permission: Permission
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
permission = Permission()
permission.askMicrophonePermission(this@MainActivity)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
permission.handlePermissionsResult(resquestCode, permissions, grantResults)
}
}
允许:
class Permission{
private val tag = "Permission message"
private val userMicrophonePermissionAgreeCode = 1
fun askMicrophonePermission(context: Context){
val currentMicrophonePermission = ActivityCompat.checkSelfPermission(context,android.Manifest.permission.RECORD_AUDIO)
if(currentMicrophonePermission != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(context as Activity, arrayOf(android.Manifest.permission.RECORD_AUDIO), userMicrophonePermissionAgreeCode)
}
fun handlePermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode){
userMicrophonePermissionAgreeCode -> {
if( grantResults[0] == PackageManager.PERMISSION_GRANTED )
Log.i(tag,"Agree microphone permission")
else
Log.i(tag,"Not agree microphone permission")
}
}
}
}