How to handle permission requests outside Activity and Fragment?
I'm developing a custom compound View that needs to access external storage. How can I implement the permission handling without involving outside parties, ie Activity or Fragment?
I get that I can request the permissions using the View's context, but how can I handle onRequestPermissionsResult()
inside the View? Is it even possible?
If it's not possible, what would be the most elegant solution to handle something like this?
I'm developing a custom compound View that needs to access external storage
IMHO, that's an architecture bug. A View
is for displaying stuff to the user, and sometimes for collecting low-level input events and turning them into higher-order constructs (eg, clicks, swipes). A View
should not have any connection to files, databases, etc. See the MVC, MVP, MVVM, and similar GUI architecture patterns.
WebView
, which does not abide by this, causes problems (eg, doing disk I/O on the main application thread) as a result.
How can I implement the permission handling without involving outside parties, ie Activity or Fragment?
You can't. It is the responsibility of the activity or fragment to request the permission, presumably before your view needs this data.
what would be the most elegant solution to handle something like this?
Extract the data-access portion of this View
into something else that is managed by the activity or fragment, where the threading, permissions, and other work associated with that data access can be managed.
It's only possible in Activities and Fragments.
What you can do is copy public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
in your View and call that method in the corresponding one in the Activity or Fragment where the Context is.
上一篇: RxJava可观察到最后一个状态