我的活动RequiresLocation
是为了请求位置服务的许可。
代码如下:
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.Button
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_requires_location.*
import java.util.jar.Manifest
class RequiresLocation : AppCompatActivity() {
val requestCode: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_requires_location)
turnOnLocationButton.setOnClickListener {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission has already been granted", Toast.LENGTH_SHORT).show()
}
else {
requestLocationPermission()
}
}
}
}
private fun requestLocationPermission(): {
ActivityCompat.requestPermissions(
RequiresLocation.class,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
requestCode) // coming up in red
}
但是 requestcode (红色)作为未解决的参考在Android Studio上显示为红色。我怎么不能通过? -是因为这是一个私有变量吗?
答案 0 :(得分:0)
使用 this@RequiresLocation
代替 RequiresLocation.class
尝试一下
ActivityCompat.requestPermissions(
this@RequiresLocation,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
requestCode)
或
private fun requestLocationPermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
requestCode) // coming up in red
}
更新
class RequiresLocation : AppCompatActivity() {
val requestCode: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_requires_location)
turnOnLocationButton.setOnClickListener {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission has already been granted", Toast.LENGTH_SHORT).show()
}
else {
requestLocationPermission()
}
}
}
private fun requestLocationPermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
requestCode) // coming up in red
}
}