|I created a small app based on a "Tabbed Activity." It has two tabs. The content of both tabs will be a
ListView filled from the Contacts database. Because of the new Permissions requirements that came out with Android 6, I need permission from the user at runtime to access that datastore. As such, I am calling
requestPermissions() as prescribed in the docs.
If I put those calls in the activity, I get one request dialog asking for permission, and because
requestPermissions() runs synchronously in a separate thread, the two fragments are allowed to finish their creation in the main thread. Once permission is granted, the activity sends both fragments a message indicating they can now populate their
ListViews. This works fine, until I restart the app. Since permission has now been granted,
requestPermissions() does not run, and the message that the activity sends to the fragments gets there before the fragments have been fully created. Just to see what would happen, I preceded the message with a 1-second sleep and that gave the fragments enough time to finish their creation. This works fine for both a first-time and restarted app. I did not like this approach because of the delay, so I kept looking.
If I put those calls in each fragment, I get two requests asking for permission. I can grant permission to neither, one or the other, or both, and the fragments will respond accordingly. The obvious problem is the two request dialogs. I could not find the proper way of having one fragment communicate to the other that it has already sought permission and that a second request is not necessary.
Another thing I tried was to put a call to
checkSelfPermission() in each fragment's
onActivityCreated() method to continuously poll the desired permission. The call to
requestPermission() was still done once in the activity. Once the permission was granted, each fragment would then go about populating its
ListView. This worked, but it still felt wrong given the pausing and polling each fragment was having to do.
I feel my first approach is the proper way to go, but cannot find a suitable solution to the timing issue. I found out a long time ago when doing Windows development that inserting code to slow down or speed up your program's execution is a major recipe for disaster. Better to signal events instead. So far I'm unable to find a comparable solution in either Java or Android.
Any helpful suggestions?
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
modified 29-Sep-17 15:37pm.