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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32097229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:39:35  来源:igfitidea点击:

Android: ActivityCompat.requestPermissions requires activity and not context :/

javaandroidsingleton

提问by Jon

I'm calling ActivityCompat.requestPermissions in order to get permissions under android M, however, this requires an activity in the argument. 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 以获取 android M 下的权限,但是,这需要参数中的活动。这很好,只是我想从单例调用它,并且单例可以被应用程序中的任何活动使用。

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. Is there a more elegant solution to this problem that I'm just not seeing?

现在,从技术上讲,我可以获取一个活动,然后在我请求许可后直接将其设置为 null,但是在我调用单例的每个活动中,这仍然给我留下了大量无用的活动参数。对于这个我没有看到的问题,是否有更优雅的解决方案?

回答by Bhargav

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

requestPermissions 上的文档说,如果您没有在清单中包含权限,则活动参数是要在其中显示弹出窗口的目标活动,为此该方法要求您传递活动而不是上下文,因为完成请求权限任务后,它会将结果返回给调用活动(即活动作为参数传递给方法)。如果您非常坚持要通过单例来实现这一点,我建议您创建一个函数来接受参数中的活动和回调,因为无论是否授予权限,您都需要处理回调