无法将变量传递给requestPermissions()

时间:2019-01-19 05:15:10

标签: android kotlin

我的活动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上显示为红色。我怎么不能通过? -是因为这是一个私有变量吗?

我正在关注official android tutorial for requestPermissions()

1 个答案:

答案 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
    }
}