简体   繁体   English

Android:ActivityCompat.requestPermissions需要活动而不是上下文:/

[英]Android: ActivityCompat.requestPermissions requires activity and not context :/

I'm calling ActivityCompat.requestPermissions in order to get permissions under android M, however, this requires an activity in the argument. 我正在调用ActivityCompat.requestPermissions以获取android M下的权限,但是,这需要参数中的活动。 This would be fine, except that I want to call it from a singleton, and the singleton can be used by any activity in the app. 这很好,除了我想从单身人士调用它,单身人士可以被应用程序中的任何活动使用。

ActivityCompat.requestPermissions(context, PERMISSIONS_LOCATION, REQUEST_LOCATION);

I want to avoid holding a reference to any activity within the singleton as that's a surefire recipe for a memory leak, and also I'd prefer that the singleton not hold an activity at all because it requires useless code in all the activities that call (every single one of them is going to have to include an extra argument in the getInstance() in order for the singleton to hold an activity - the singleton needs to get the activity from somewhere ). 我想避免对单例中的任何活动进行引用,因为这是内存泄漏的可靠方法,而且我更喜欢单例根本不进行活动,因为它在所有调用的活动中都需要无用的代码(他们中的每一个都必须在getInstance()中包含一个额外的参数,以便单例持有一个活动 - 单例需要从某个地方获取活动。

Now, I can technically get an activity and then set it to null straight after I request the permission, however that still leaves me with tons of useless activity arguments in every single activity where I make a call to the singleton. 现在,我可以在技术上获得一个活动,然后在我请求许可后将其设置为null,但是在我调用单例的每个活动中,仍然会留下大量无用的活动参数。 Is there a more elegant solution to this problem that I'm just not seeing? 是否有一个更优雅的解决方案,我只是没有看到这个问题?

The documentation on requestPermissions says that the activity parameter is the target activity where you want to show the pop up if you haven't included the permission in your manifest and for this purpose that method requires you to pass an activity and not the context, because upon finish the request permissions task it will then return a result to the calling activity(that is the activity passed as the parameter to the method). requestPermissions上的文档说,如果您没有在清单中包含权限,则活动参数是您要显示弹出窗口的目标活动,为此目的,该方法要求您传递活动而不是上下文,因为完成请求权限任务后,它将结果返回给调用活动(即作为参数传递给方法的活动)。 If you are so adamant about implementing this through your singleton I suggest you create a function that accepts the activity in the parameter and the callbacks too as you WILL need to handle the callbacks if the permissions were given or not 如果你坚持通过你的单例实现这个,我建议你创建一个接受参数和回调中的活动的函数,因为如果给出了权限,你将需要处理回调

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

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