提问人:Zorgan 提问时间:1/18/2019 最后编辑:Vadim KotovZorgan 更新时间:2/26/2020 访问量:451
Android checkSelfPermission() 中的“this”指的是什么?
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)
这里的上下文具体指的是什么?是整个应用程序,还是活动?
答:
Context
是有关应用程序的全局信息的接口 环境。这是一个抽象类,其实现是 由Android系统提供。它允许访问 特定于应用程序的资源和类,以及 应用程序级操作,例如启动活动、 广播和接收意图等。
您可以通过不同的方法获得context
- getApplicationContext()
- getContext() 的
- getBaseContext()
- this(在 Activity 类中时)
this
-> 是指当前活动的上下文。
我想知道这个关键字在下面的代码中指的是什么
在代码片段中
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
关键字引用当前实例。this
Activity
对于我们当中那些习惯于编写 Java 代码的人来说:在这种情况下,Kotlin 与 Java 不同。
在 Java 中,一旦你“进入”了 .RequiresLocation.this
View.OnClickListener
在 Kotlin 中,只需 即可。但是,如果您使用的是 Android Studio 或 IntelliJ Idea 并通过在 this 之后立即输入 @ 继续输入,那么代码完成将为您提供 ,因此您可以确定它确实是正确的。this
this@RequiresLocation
this
中的参数指的是什么?Context
checkSelfPermission()
你可以传入任何 - an , the , 但也可以传入某种类型的 (请注意,根据文档,两者都从中扩展,有 7 个直接子类和 40 多个间接子类,其中一个是 .所有这些都是 的有效参数。Context
Activity
Application
Service
Application
Service
ContextWrapper
Activity
checkSelfPermission()
评论
RequiresLocation.this
将。this@RequiresLocation
Kotlin
it
it
onClick(view:View)
it.
)
它引用 RequiresLocation 类的当前实例。
完全限定会读得更清楚,例如:RequiresLocation.this
因此,正如您所注意到的,checkSelfPermission 的签名需要一个 Context,而“this”(RequiresLocation 的实例)可以作为这样的上下文参数传递,因为所有 Activity 都派生自 Context。 请注意,由于 RequiresLocation 派生自 AppCompatActivity,因此此类也是一个 Context。
上下文是指当前活动状态。我们使用上下文来获取当前活动状态的信息。 您还可以参考以下链接以获取有关上下文的详细信息。https://blog.mindorks.com/understanding-context-in-android-application-330913e32514
评论