Reputation: 165
I want to create a askMicrophonePermission
function in Permission.class
.
And write Permission().askMicrophonePermission()
in onCreate()
.
I don't known how to change this so that ActivityCompat.checkSelfPermission
and ActivityCompat.requestPermissions
can run in the
Permission().askMicrophonePermission()
.
Here is my code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Permission().askMicrophonePermission()
}
}
class Permission {
fun askMicrophonePermission(){
val userMicrophonePermissionAgreeCode = 1
val currentMicrophonePermission = ActivityCompat.checkSelfPermission(_________,android.Manifest.permission.RECORD_AUDIO)
if (currentMicrophonePermission != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(_______________, arrayOf(android.Manifest.permission.RECORD_AUDIO), userMicrophonePermissionAgreeCode)
}
}
}
Upvotes: 10
Views: 31477
Reputation: 15336
You can harness the power of companion object
in Kotlin and create static methods like Java.
private companion object {
fun askMicrophonePermission(context: Context) {
val userMicrophonePermissionAgreeCode = 1
val currentMicrophonePermission = ActivityCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO)
if (currentMicrophonePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context, arrayOf(android.Manifest.permission.RECORD_AUDIO), userMicrophonePermissionAgreeCode)
}
}
}
And then you use it like
ClassName.askMicrophonePermission(this@YouActivity)
Upvotes: 3
Reputation: 75788
You can use below
For KOTLIN
this
replaced by this@MainActivity
You should set
Permission().askMicrophonePermission(this@MainActivity)
Then Pass Context.
fun askMicrophonePermission(context: Context)
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system.
FYI
In a member of a class, this
refers to the current object of that class.
Upvotes: 28