简体   繁体   English

Android Studio-ActivityCompat.requestPermissions中“ this”的正确用法是什么?

[英]What is the correct usage of “this” in Android Studio - ActivityCompat.requestPermissions?

In using the method below, Android Studio is generating the following error on the keyword "this": 在使用以下方法时,Android Studio在关键字“ this”上生成以下错误:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_READ_FINE_LOCATION);

Error: 错误:

Wrong first argument type...found com.websmithing.wp.gpstracker.LocationService, required android.app. 错误的第一个参数类型...找到com.websmithing.wp.gpstracker.LocationService,需要android.app。 Activity 活动

I can reference the activity using "this" without any error when evaluating the manifest file permissions check as per below. 评估清单文件权限检查时,我可以使用“ this”引用活动,而没有出现以下错误。

ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)   !=
  PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
  PackageManager.PERMISSION_GRANTED) {

Can anyone point me in the right direction? 谁能指出我正确的方向?

this refers to the present class. this是指当前阶级。 It only works with this when you are in an activity while requesting permission. 仅当您在活动中同时请求许可时, this才适用。

Solution

Send a notification from the service so when the user clicks it, open the activity and ask for the permissions you need. 发送来自服务的通知,以便当用户单击它时,打开活动并询问您所需的权限。

How do I send a notification? 如何发送通知?

Simple refer to Building a Notification . 简单参考构建通知

Pay attention to the error message. 请注意错误消息。 It's pointing you toward the solution. 它为您提供了解决方案。

Wrong first argument type...found com.websmithing.wp.gpstracker.LocationService, required android.app. 错误的第一个参数类型...找到com.websmithing.wp.gpstracker.LocationService,需要android.app。 Activity 活动

It means that ActivityCompat.requestPermissions() is expecting an Activity as the first argument but you are providing a LocationService instance. 这意味着ActivityCompat.requestPermissions()期望将Activity作为第一个参数,但是您要提供LocationService实例。 I guess you are invoking this from an inner class, then perhaps you have to use WhateverYouActivityClassIs.this to refer to the outer class. 我想您是从内部类调用此函数,那么也许您必须使用WhateverYouActivityClassIs.this来引用外部类。

您必须在调用该类的活动中编写checkSelfpermission代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM