Search Unity

[Open Source] AndroidRuntimePermissions - manage runtime permissions "synchronously" on Android M+

Discussion in 'Assets and Asset Store' started by yasirkula, Apr 28, 2018.

  1. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Last edited: May 31, 2023
    y01cu likes this.
  2. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Now available on Asset Store!
     
  3. multimediamarkers

    multimediamarkers

    Joined:
    Feb 17, 2016
    Posts:
    49
    This is really a good and simple plugin to manage the permissions on several Android devices!
     
    yasirkula likes this.
  4. drordoit

    drordoit

    Joined:
    Sep 7, 2013
    Posts:
    36
    Hi , thanks for the plugin.
    I don't have much experience in the permissions , and i can't get it to work.
    I tried :
    Code (CSharp):
    1. AndroidRuntimePermissions.RequestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    2.         Debug.Log(AndroidRuntimePermissions.CheckPermission("android.permission.WRITE_EXTERNAL_STORAGE") + " <==permission status");
    I never got a "permission box" on android and keep getting "Denied".
    Is the code right? can you add an example how to do it right?
    Thanks again .
    Dror
     
    moscas99 likes this.
  5. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Yes your code is correct. Though, you can directly Debug.Log the result of RequestPermission. So, CheckPermission is redundant here.

    For runtime permissions to work correctly, you have to declare the permission in AndroidManifest first. For WRITE_EXTERNAL_STORAGE, this can be achieved by setting Write Permission to External (SDCard) in Player Settings.
     
  6. drordoit

    drordoit

    Joined:
    Sep 7, 2013
    Posts:
    36
    I got "AndroidManifest" in the assets/Plugins/Android folder, with the line :
    Code (CSharp):
    1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
    As you suggested I went to the player setting and changed the "Write Permission" to "External (SDCard)", and still no Permission popup and the debug show "Denied".
    Can you assume the reason?
     
  7. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    After building your project to Android, can you check the contents of PROJECT_PATH/Temp/StagingArea/AndroidManifest.xml and see if android:maxSdkVersion="18" is still there? If so, try removing that part from your manifest. It basically adds WRITE_EXTERNAL_STORAGE permission to devices with API version less than or equal to 18. So, if your device has a newer Android version, it won't have WRITE_EXTERNAL_STORAGE permission. BTW, may I ask your Android version?

    P.S. Also check Settings/YOUR_APP/Permissions to see if Storage permission is available there.
     
  8. drordoit

    drordoit

    Joined:
    Sep 7, 2013
    Posts:
    36
    Ok, finally things are starting to happen.
    I removed the "android:maxSdkVersion="18" from the manifest in the SDK
    And now permission is Granted! Will I have a side effects from removing that line?
    I still cant save my screenshot into my phone , but at list now I know I have permission :).
    p.s - I have Android version 8.0.0
     
  9. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Other than adding a "Storage: Modify or delete the contents of your USB storage" permission description to your permissions list in Google Play, there won't be any side effects.

    If your app saves screenshots to a public directory like Gallery, then you have to have WRITE_EXTERNAL_STORAGE permission no matter which API it is, so you should be good to go. But if your app saves the screenshots to a private directory like Application.temporaryCachePath, then you won't be needing WRITE_EXTERNAL_STORAGE permission for this.
     
  10. drordoit

    drordoit

    Joined:
    Sep 7, 2013
    Posts:
    36
    I'm saving to "persistentDataPath", and I got WRITE_EXTERNAL_STORAGE permission and still it's fail (Works great in unity).
     
  11. drordoit

    drordoit

    Joined:
    Sep 7, 2013
    Posts:
    36
    It's working!!!!!!! Thanks a lot for you're patinas and help!
     
    yasirkula likes this.
  12. Accused

    Accused

    Joined:
    Apr 28, 2015
    Posts:
    6
    Hello, I am trying to get coarse gps for a lwp made with uLiveWallpaper. I get this when the Check for permissions is called:


    AndroidJavaException: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkSelfPermission(java.lang.String)' on a null object reference
    java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkSelfPermission(java.lang.String)' on a null object reference
     
  13. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
  14. Accused

    Accused

    Joined:
    Apr 28, 2015
    Posts:
    6
    Thank you for your prompt reply!
    I got curious and checked how Google has their Earth LWP since I know it uses the gps. They call it on the preview activity so I image you can't call it from the wallpaper service. I was able to quickly write a call for the gps on the preview activity.
     
  15. eestradaRAS

    eestradaRAS

    Joined:
    Apr 2, 2018
    Posts:
    4
    Excuse me. For Some reason asking for Camera Permission also asking to access multimedia files in the device, which is odd, and I was wondering if it is a common occurence
    Any clues?


    The only call I am making is:
    Code (CSharp):
    1.  
    2. public void OnFindAFactPressed(){
    3.         #if UNITY_IOS && !UNITY_EDITOR
    4.         iOSCameraPermission.VerifyPermission(gameObject.name, "OnIOSPermisionCallback");
    5.         #elif UNITY_ANDROID
    6.         AndroidRuntimePermissions.Permission result = AndroidRuntimePermissions.RequestPermission( "android.permission.CAMERA" );
    7.         if( result == AndroidRuntimePermissions.Permission.Granted ) {
    8.             OnAndroidPermission(true);
    9.         }
    10.         else {
    11.             OnAndroidPermission(false);
    12.         }
    13.            
    14.         #elif UNITY_EDITOR
    15.         _uiManager.Pop();
    16.         _uiManager.Push("SnapTarget");
    17.         #endif
    18.     }
    19.  
    Thank you beforehand.
     
  16. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    That's unexpected for me. I couldn't find any leftover code that might have caused this issue, so I'm really unsure about the cause of it.
     
  17. jdgauchat

    jdgauchat

    Joined:
    Jun 24, 2017
    Posts:
    18
    You are the man!

    Thanks!
    JD
     
    yasirkula likes this.
  18. MykytaTilininNix

    MykytaTilininNix

    Joined:
    Oct 5, 2018
    Posts:
    1
    Hello
    I have a problem. I added the following line to manifest:
    Code (CSharp):
    1. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    but permission dialog had shown wneh i start the app and i dont want this
    I googled on Unity Documentation and add the following:
    Code (CSharp):
    1. <meta-data android:name="unityplayer.SkipPermissionsDialog" android:value="true" />
    But now this code
    Code (CSharp):
    1. Debug.Log("Permission"  + AndroidRuntimePermissions.CheckPermission("android.permission.READ_EXTERNAL_STORAGE"));
    just always returns denied
    I think the SkipPermissionDialog option just skip dialog any time and not only on app start, but how to make it correctly?
     
  19. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Probably the permission result is cached as Denied. Try uninstalling the app and then reinstalling it.
     
  20. Archviz3d

    Archviz3d

    Joined:
    Apr 4, 2016
    Posts:
    92
    Awesome asset!! Many thanks :) for IOS do you plan to have anything similar? Thanks
     
  21. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Thanks! Currently, I don't have any plans for iOS :/
     
  22. writetoleopaul

    writetoleopaul

    Joined:
    Jul 6, 2018
    Posts:
    3
    Oct 7th, 1:08PM
    Hey Yasirkula,
    I'm new to unity AR, I tried to develop an AR App, But camera not opening, As told "Simply import RuntimePermissions.unitypackage to your project and you are good to go!" in the Assetstore link, I did this, but no permission is being asked for camera after importing the plugin to Assets and building it. What should I do? Is there a code to be added? If there, Can you tell me where to find one? I looked into whole package but in vain found nothing. I really wish you can help me out. Thanks a lot :)

    Oct 7th, 5:29 PM
    I used your plugin Native Plugin Gallery For Android and I found script from the same page. I was able to take a screenshot and send it to gallery. Link: (https://stackoverflow.com/questions...red-photo-from-unity-in-android-image-gallery). That's the code I used. Now, I understand that we need to use a code to call the permissions as well. Is that available in the Plugin? Can you tell me where to find it? Please do help. Thanks a lot again @yasikurla.
     
    Last edited: Dec 7, 2018
  23. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    You should first add that permission (android.permission.CAMERA) to Assets/Plugins/Android/AndroidManifest.xml. Then, you can use the following code to request the camera permission at runtime:

    Code (CSharp):
    1. AndroidRuntimePermissions.Permission result = AndroidRuntimePermissions.RequestPermission( "android.permission.CAMERA" );
    2. if( result == AndroidRuntimePermissions.Permission.Granted )
    3.     Debug.Log( "We have permission to access the camera!" );
    4. else
    5.     Debug.Log( "Permission state: " + result ); // No permission
     
  24. writetoleopaul

    writetoleopaul

    Joined:
    Jul 6, 2018
    Posts:
    3
    Oct 8th, 3:15 PM,

    Thank you @yasirkula

    Oct 9th, 3:35 PM,

    As said above, I added the code you have said to the script I have got. The code in full for now is

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.IO;
    public class ScreenshotTaker : MonoBehaviour
    {
    public bool takingScreenshot = false;
    public void CaptureScreenshot()
    {
    StartCoroutine(TakeScreenshotAndSave());
    }
    private IEnumerator TakeScreenshotAndSave()
    {
    takingScreenshot = true;
    yield return new WaitForEndOfFrame();
    Texture2D ss = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
    ss.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
    ss.Apply();
    // Save the screenshot to Gallery/Photos
    string name = string.Format("{0}_Capture{1}_{2}.png", Application.productName, "{0}", System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
    Debug.Log("Permission result: " + NativeGallery.SaveImageToGallery(ss, Application.productName + " Captures", name));
    takingScreenshot = false;
    }
    // adding the code you have told me to add from next line
    AndroidRuntimePermissions.Permission result = AndroidRuntimePermissions.RequestPermission( "android.permission.CAMERA" );
    if( result == AndroidRuntimePermissions.Permission.Granted )
    Debug.Log( "We have permission to access the camera!" );
    else
    Debug.Log( "Permission state: " + result );
    }


    However, The Console says that there are errors in it, namely,
    "Assets/ScreenshotTaker.cs(32,2): error CS1519: Unexpected symbol `if' in class, struct, or interface member declaration", "Assets/ScreenshotTaker.cs(32,13): error CS1519: Unexpected symbol `==' in class, struct, or interface member declaration", "Assets/ScreenshotTaker.cs(32,60): error CS1519: Unexpected symbol `)' in class, struct, or interface member declaration"
    "Assets/ScreenshotTaker.cs(33,14): error CS1519: Unexpected symbol `(' in class, struct, or interface member declaration"
    "Assets/ScreenshotTaker.cs(33,57): error CS1519: Unexpected symbol `We have permission to access the camera!' in class, struct, or interface member declaration"
    "Assets/ScreenshotTaker.cs(35,14): error CS1519: Unexpected symbol `(' in class, struct, or interface member declaration"
    "Assets/ScreenshotTaker.cs(35,35): error CS1519: Unexpected symbol `Permission state: ' in class, struct, or interface member declaration"
    "Assets/ScreenshotTaker.cs(35,46): error CS1519: Unexpected symbol `)' in class, struct, or interface member declaration".

    Do you get to know why these errors have come up? I'm pretty sure I have missed somethings. I do not understand why. Should I be adding the script somewhere? Should I be creating a new script and then add the script (not sure where to add) you have given me?

    I opened my Manifest file and I did see the code <uses-permission android:name="android.permission.CAMERA"/>. I hope this is what you have told me to add in the Manifest file.

    I did not understand what this sentence meant from your reply "you can use the following code to request the camera permission at runtime:"

    I'm very sorry for the elaborate problem, But thanks for the code, I will do my best to figure this out. I gotta learn C#. I hope you can help me out again. Thanks a lot again :)

    Regards,
    Leo Paul.
     
    Last edited: Dec 8, 2018
  25. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    You should use my code in a function. For example, you can move it inside the CaptureScreenshot() function:

    Code (CSharp):
    1. public void CaptureScreenshot()
    2. {
    3.     StartCoroutine(TakeScreenshotAndSave());
    4.    
    5.     AndroidRuntimePermissions.Permission result = AndroidRuntimePermissions.RequestPermission( "android.permission.CAMERA" );
    6.     if( result == AndroidRuntimePermissions.Permission.Granted )
    7.         Debug.Log( "We have permission to access the camera!" );
    8.     else
    9.         Debug.Log( "Permission state: " + result ); // No permission
    10. }
    In reality, though, you should put my code before attempting to access the Camera and only activate the camera (AR) if the result is equal to AndroidRuntimePermissions.Permission.Granted.
     
  26. Gluxable

    Gluxable

    Joined:
    Oct 31, 2017
    Posts:
    2
    hey @yasirkula, as of unity 2018.3 unity does no longer automatically request permissions at app start. I am trying to test the permission with your example code but nothing seems to happen
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. #if PLATFORM_ANDROID
    4. using UnityEngine.Android;
    5. #endif
    6.  
    7. public class LocationPermissionScript : MonoBehaviour
    8. {
    9.     public Text debugTxt;
    10.     private void Start()
    11.     {
    12.         AndroidRuntimePermissions.Permission result =
    13.             AndroidRuntimePermissions.RequestPermission("android.permission.RECORD_AUDIO");
    14.  
    15.         debugTxt.text = result.ToString();
    16.     }
    17.  
    18. }
    I added a debug text to check the result but it is blank. I have added the <uses-permission android:name="android.permission.RECORD_AUDIO" /> in the Plugins/Android/AndroidManifest.xml
     
  27. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Your code looks correct. Does the auto-generated PROJECT_PATH/Temp/StagingArea/AndroidManifest.xml file also contain RECORD_AUDIO permission after building your project to Android? Are there any error messages? You can use this plugin to see debug/error messages at runtime (I'd recommend you to enable logcat logs in that plugin, as well): https://forum.unity.com/threads/in-game-debug-console-open-source.411323/
     
  28. Gluxable

    Gluxable

    Joined:
    Oct 31, 2017
    Posts:
    2
    Yep, the permissions are also in the staging area manifest. There are no errors :/
     
  29. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    What happens when you change the debug text like this:
    debugTxt.text = "" + ( (int) result );


    If nothing happens, does setting the text to something like "Hello world" actually change the text?
     
  30. Anuragsingh54854

    Anuragsingh54854

    Joined:
    Aug 3, 2018
    Posts:
    4
    Please describe in detail how to add read and write permission in my game.
     
  31. Anuragsingh54854

    Anuragsingh54854

    Joined:
    Aug 3, 2018
    Posts:
    4
    I am using Unity Pro 5.6.f1 so will this plugin work on that version and if it will work then please tell me because I am searching for this long time.
     
  32. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    StarArcher and Anuragsingh54854 like this.
  33. Anuragsingh54854

    Anuragsingh54854

    Joined:
    Aug 3, 2018
    Posts:
    4
    You came in my game dev journey as the GOD. Thanks for your work and this fast support.
    Hope you may also get success in your life.
    Once again a big THAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANK to you.
    Quite happy.
    And yes it worked for me and if anyone wants its video basically for beginners to know how it works just email me at anuragsingh54854@gmail.com and I will make a video on that because it's quite good for those who want a good plugin and also for them whose pocket is quite tight(like me).
    And yuup thanks again one more time.
     
  34. Anuragsingh54854

    Anuragsingh54854

    Joined:
    Aug 3, 2018
    Posts:
    4
    And of course some smilies:):):):):):):):):):):):):):):):););););)
     
    yasirkula likes this.
  35. TypeFunDiabetes

    TypeFunDiabetes

    Joined:
    Mar 3, 2014
    Posts:
    2
    Love the asset! But I'm having trouble getting the permission window to pop up. Using your sample code, the screen just freezes for a few seconds when CheckStoragePermission() is called. After a few seconds it moves on, but no user prompt pops up. Spent all day trying to troubleshoot but I'm at the end of my rope! Any advice?

    Running on Pixel 2 XL with Android 9. Android Manifest contains the line
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     
  36. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Does the plugin return Denied permission? Are there any parental control sort of things set up in your device? Does the issue also occur on an emulator that uses an older Android version? Is the Storage permission visible in the app's Permission Settings? What happens when you toggle it on/off? Are there any meaningful error messages in Logcat?
     
  37. justtime

    justtime

    Joined:
    Oct 6, 2013
    Posts:
    424
    Hi there! Great plugin, but seems that it works for me only in Dev build mode.
    Unity 2017.4.21f, Android arm build
     
    Last edited: Mar 5, 2019
  38. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Is this behaviour persistent across different devices/emulators? Are there any meaningful error messages in Logcat? On Release builds, do the permission function(s) simply return Denied without ever showing the permission dialog? What happens when you first uninstall the app manually and then build the Unity project?
     
  39. justtime

    justtime

    Joined:
    Oct 6, 2013
    Posts:
    424
    Hi! I solved it. Just added line in proguard file for prevent stripping.
     
    yasirkula likes this.
  40. themalakarraja

    themalakarraja

    Joined:
    Nov 26, 2017
    Posts:
    3
    Hello!! I'm using your UnityAndroidRuntimePermissions plugin in my project. It is pretty good. Is there any way that I can do something similar for iOS?
     
  41. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Each iOS permission is requested in a different way, so to support iOS, I'd have to implement all these functions manually (e.g. checking camera permission and checking Photos permission). Though, I don't think you should be worried about iOS permissions since iOS plugins accessing features that need permission (e.g. Photos, camera) will probably request the permissions internally.
     
  42. warraich

    warraich

    Joined:
    Mar 11, 2016
    Posts:
    3
    @yasirkula i have integrated your plugin .... when i bring manifest file in my project my application crashes. Can you help?
     
  43. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    I don't know why it would crash, assuming that you're copying the default AndroidManifest.xml to the Assets/Plugins/Android folder. Does it not crash if you delete that AndroidManifest?
     
  44. warraich

    warraich

    Joined:
    Mar 11, 2016
    Posts:
    3
    i just copied manifest file from my other projects. before seeing this post i didn't had any manifest it wasn't crashing then but no permission dialoge was showing then i added manifest filenow it doesn't even show unity logo and crashes the app
     
  45. warraich

    warraich

    Joined:
    Mar 11, 2016
    Posts:
    3
    @yasirkula can u tell me what should be the minimum Api level in player settings and minimum sdk version in manifest please?
     
  46. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    You don't need to specify a minimum sdk/api level for this plugin. Instead of copying your other project's AndroidManifest, try copying the default one from C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Apk.
     
  47. Tempest74

    Tempest74

    Joined:
    May 17, 2017
    Posts:
    133
    Hey, I need your help. I have this code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PermissionViaPlugin : MonoBehaviour
    6. {
    7.     void Awake()
    8.     {
    9.         AndroidRuntimePermissions.RequestPermission("android.permission.RECORD_AUDIO");
    10.     }
    11. }
    12.  
    I use latest stable version of unity and I run it on unity remote 5. I do not receive any permission box and my microfone does not look like it is recording. Android version 8 or 9, I have no real idea.
    And the manifest I copied in the way you said to me (btw under Packages I made my own Android folder:
    Code (CSharp):
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <manifest
    3.     xmlns:android="http://schemas.android.com/apk/res/android"
    4.     package="com.unity3d.player"
    5.     xmlns:tools="http://schemas.android.com/tools"
    6.     android:installLocation="preferExternal">
    7.     <supports-screens
    8.         android:smallScreens="true"
    9.         android:normalScreens="true"
    10.         android:largeScreens="true"
    11.         android:xlargeScreens="true"
    12.         android:anyDensity="true"/>
    13.  
    14.     <application
    15.         <meta-data android:name="unityplayer.SkipPermissionsDialog" android:value="true" />
    16.         android:theme="@style/UnityThemeSelector"
    17.         android:icon="@mipmap/app_icon"
    18.         android:label="@string/app_name">
    19.         <activity android:name="com.unity3d.player.UnityPlayerActivity"
    20.                   android:label="@string/app_name">
    21.             <intent-filter>
    22.                 <action android:name="android.intent.action.MAIN" />
    23.                 <category android:name="android.intent.category.LAUNCHER" />
    24.             </intent-filter>
    25.             <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    26.         </activity>
    27.     </application>
    28. </manifest>
    29.  
    And I want to require a permission to write some data on player device. what should I do
     
  48. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    You need to add the following line inside
    <manifest>...</manifest>
    :

    <uses-permission android:name="android.permission.RECORD_AUDIO">


    To write data on external storage, you need the
    android.permission.WRITE_EXTERNAL_STORAGE
    permission.

    P.S. I don't know if using any AndroidManifest other than Assets/Plugins/Android/AndroidManifest.xml works.
     
  49. Tempest74

    Tempest74

    Joined:
    May 17, 2017
    Posts:
    133
    I did not have it in my folder. So i copied it as I found someone said here: https://github.com/yasirkula/UnityAndroidRuntimePermissions . But the Android folder from Assets/Plugins/Android was missing. I created one. It this okay? I will try to make the change you suggested as soon as possible and come back with a feedback
     
  50. Tempest74

    Tempest74

    Joined:
    May 17, 2017
    Posts:
    133
    this behaviours occurs: I do use unity remote 5. I do not get any error or permission request but it seems like my microphone is working. But I do not know if my laptop microphone or phone microphone due to fact that my phone is plugged close to my laptop. Is this normal? Am I missing something?