android - Android checkSelfPermission()中的 "this"指的是什么?

标签 android kotlin this android-context

我想知道下面代码中的 this 关键字指的是什么(代码块是请求访问用户位置的权限)。

class RequiresLocation : AppCompatActivity() {

    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){
                ...
            }
        }
    }
}

我检查了 Android 文档中的 checkSelfPermission(),它有这个:

int checkSelfPermission (Context context, 
                String permission)

这里的上下文具体指的是什么?是整个应用程序而不是 Activity 吗?

最佳答案

I'm wondering what the this keyword refers to in the below code

在你的代码 fragment 中

ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED

关键字this引用当前的Activity实例。

对于我们这些习惯于编写 Java 代码的人来说:在这种情况下,Kotlin 不同于 Java。

在 Java 中,一旦您“处于”View.OnClickListener 的范围内,就必须编写 RequiresLocation.this

在 Kotlin 中,只需 this 即可。但是,如果您正在使用 Android Studio 或 IntelliJ Idea 并通过在 this 之后输入 @ 继续键入,那么代码完成将为您提供 this@RequiresLocation ,因此您可以确定它确实是正确的 this

checkSelfPermission() 中的Context 参数指的是什么?

您可以传入任何 Context - ActivityApplication,以及某种类型的 Service (注意 ApplicationService 都从 ContextWrapper 扩展,根据 docs 有七个直接子类和 40 多个间接子类,其中之一它们是 Activity。它们都是 checkSelfPermission() 的有效参数。)

关于android - Android checkSelfPermission()中的 "this"指的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54244142/

相关文章:

java - "Arrays.copyOf"在 Kotlin

kotlin - 是否可以动态更改实例的方法?

jquery - 'this' 的 4 种不同场景。正确的解释是什么?

android - Google Play 控制台 - 无法编辑草稿

android - Android中选择、检查和激活的状态有什么区别?

hibernate - 无法使用和另一个And Or一起使用条件api构建查询

javascript - this 内部嵌套函数

c++ - 智能指针 + "this"被认为是有害的?

AndroidManifest.xml 文档中跟在根元素之后的标记必须格式正确

android - 如何在不使用 Action Bar 的情况下显示三点菜单?