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

What does "this" refer to in Android checkSelfPermission()?

我想知道下面代码中的 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?

Context is Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

获得context

的不同方法
  1. getApplicationContext()
  2. getContext()
  3. getBaseContext()
  4. 这个(在 activity class 时)

this -> 引用当前activity.

的上下文

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

在您的代码片段中

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

关键字this指的是当前Activity实例。

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

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

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

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

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

它指的是RequiresLocation class.

当前实例

完全合格会读得更清楚,例如:RequiresLocation.this

因此,正如您注意到 checkSelfPermission 的签名需要 Context 和“this”(RequiresLocation 的实例)可以作为此类上下文参数传递,因为所有 A​​ctivities 都派生自 Context。 考虑到由于 RequiresLocation 派生自 A​​ppCompatActivity,因此 class 也是一个 Context .

上下文 指的是当前activity 状态。我们使用上下文来获取当前 activity 状态的信息。 您还可以参考下面的 link 以获取有关 Context 的详细信息。 https://blog.mindorks.com/understanding-context-in-android-application-330913e32514