[100 Unity pit tips] | Unity calls the API to dynamically obtain Android permissions, with all Android permission forms attached

Posted by suzuki on Thu, 10 Mar 2022 12:06:50 +0100

Unity Science

Old rules, let's first introduce Unity's popular science knowledge:

  • Unity is a real-time 3D interactive content creation and operation platform.
  • All creators, including game development, art, architecture, automobile design and film and television, turn creativity into reality with Unity.
  • Unity platform provides a complete set of software solutions that can be used to create, operate and realize any real-time interactive 2D and 3D content. The supporting platforms include mobile phones, tablets, PC s, game consoles, augmented reality and virtual reality devices.
  • Unity can also be simply understood as a game engine, which can be used to professionally make games!

Unity steps on the pit to learn small knowledge points

Unity calls the API to dynamically obtain Android permissions

When developing Android applications, the problem of obtaining Android permissions is often used.

There are two solutions to this problem

  • One is that the method of dynamically obtaining permissions has been written on the Android side, and Unity can call this method.
  • The other is to call API directly in Unity and apply for permission access (after 2019, Unity has already provided Android oriented permissions).

For Unity developers, it's convenient to directly call API on Unity side to apply for permission. Here's how to call it.
If you want to know the first method, you can see this article: How Unity interacts with Android Studio ✨ Obtain mobile phone permission (storage, recording, camera, etc.)

Unity official API link: https://docs.unity3d.com/ScriptReference/Android.Permission.html

Click the source code to see that Unity also has permission names, which means that we can also customize some permissions to pop-up windows, and we don't have to use them.

The API provided by Unity can be called directly in the script. Examples of API usage are as follows:

    private void Start()

The following is a complete example code of using Unity to dynamically apply for permission:

The first scheme:

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Android;

public class PerTest : MonoBehaviour
    string[] strs = new string[] {

    void Start()
        for (int i = 0; i <= strs.Length - 1; i++)
            Debug.Log("add permission: " + strs[i]);

The second scheme:

using System.Linq;
using UnityEngine;
using UnityEngine.Android;

public class PerTest : MonoBehaviour
    //An array of strings for which you want permission
    string[] strs = new string[] {

    void Start()
        //Start dynamic request permission
        strs.ToList().ForEach(s => {
            Debug.Log("RequestUserPermission: "+s);
            if (!Permission.HasUserAuthorizedPermission(s))

            Debug.Log("add RequestUserPermission: " + s);
                Debug.Log("it has RequestUserPermission: " + s);

The third scheme:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;

public class PerTest : MonoBehaviour
    public static PerTest instance;
    private void Awake()
        instance = this;
    //Initialization, permission application should be made as early as possible
    public static void Init()
        //First add the permission to the list, and then apply
        AndroidPermissionMgr.StartCheckPermission(0.02f); //Start application

        Debug.Log("Permission application completed");
public static class AndroidPermissionMgr
    static int index;
    public static List<string> permissionList = new List<string>();

    public static void StartCheckPermission(float time)
        Debug.Log("Start permission application");
        if (permissionList.Count > 0)
            Get(permissionList[index], time);

    /// <summary>
    ///External access method
    /// </summary>
    ///< param name = "type" > permission name < / param >
    ///< param name = "time" > if you refuse, how long is the delay to apply again < / param >
    static void Get(string type, float time)
        if (!Permission.HasUserAuthorizedPermission(type))
            Debug.Log("Obtaining permissions for:" + type);
            PerTest.instance.StartCoroutine(Check(type, time));
            Debug.Log("Permission obtained:" + type);

            if (index < permissionList.Count - 1)
                index += 1;
                Get(permissionList[index], time);
    static IEnumerator Check(string type, float time)
        yield return new WaitForSeconds(time);
        Get(type, time);

The pop-up window of the three schemes has the same effect, and different permissions can be added according to different permission requirements.

The following is all the Android permission tables you can refer to.

Android common permissions sorting

<!--Connection network permission, used to perform cloud voice capability -->
<uses-permission android:name="android.permission.INTERNET"/>
<!--Obtain the permission to use the mobile phone recorder. This permission is required for dictation, recognition and semantic understanding -->
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!--Read network information status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--Get current wifi state -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!--Allow programs to change network connection status -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<!--Permission to read mobile phone information -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!--Read contact permission, which is required for uploading contacts -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<!--Write permission for external storage, which is required for building syntax -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--External storage read permission, which is required for building syntax -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<!--Configuration permission is used to record application configuration information -->
<uses-permission android:name="android.permission.WRITE_SETTINGS"
    tools:ignore="ProtectedPermissions" />
<!--Mobile positioning information is used to provide positioning for semantic and other functions and provide more accurate services-->
<!--Location information is sensitive information, which can be accessed through Setting.setLocationEnable(false)Close location request -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!--If you need to use camera head, you also need to use photo recognition -->
<uses-permission android:name="android.permission.CAMERA" />

Android dangerous permissions

numberPermission groupjurisdiction

Android all permissions

Serial numberjurisdictionexplain
001ACCESS_CHECKIN_PROPERTIESAllow read-write access to the "properties" table in the checkin database,
The value can be modified and uploaded
002ACCESS_COARSE_LOCATIONAllow a program to access CellID or WiFi hotspots to get a rough location
003ACCESS_FINE_LOCATIONAllow a program to access CellID or WiFi hotspots to get a rough location
004ACCESS_LOCATION_EXTRA_COMMANDSAllow applications to access additional locations to provide commands
005ACCESS_NETWORK_STATEAllows the program to obtain network information status, such as whether the current network connection is valid
006ACCESS_NOTIFICATION_POLICYTag permissions for applications that want to access notification policies
007ACCESS_WIFI_STATEAllow the program to obtain the current WiFi access status and WLAN hotspot information
008ACCOUNT_MANAGERAllow the program to access account management through account authentication
ACCOUNT_MANAGER related information
009ADD_VOICEMAILAllow an application to add a voice mail system
010BATTERY_STATSAllow programs to update phone battery statistics
011BIND_ACCESSIBILITY_SERVICERequest the accessibilityservice service to ensure that only the system can bind to it
012BIND_APPWIDGETAllow the program to tell the appWidget service that it needs to access the database of the widget. Only very few applications use this permission
013BIND_CARRIER_MESSAGING_SERVICEUse when API level is higher than 23, otherwise use BIND_CARRIER_SERVICES
014BIND_CARRIER_SERVICESSystem processes that allow binding to services in operator applications will have this permission
015BIND_CHOOSER_TARGET_SERVICEIt must be required by ChooserTargetService to ensure that only the system can bind to it
016BIND_DEVICE_ADMINRequest the system administrator receiver. Only the system can use it
017BIND_DREAM_SERVICEIt must be required by a DreamService to ensure that only the system can bind to it
018BIND_INCALL_SERVICEIt must be required by a MidiDeviceService to ensure that only the system can bind to it
019BIND_INPUT_METHODRequest InputMethodService service, which can only be used by the system
020BIND_MIDI_DEVICE_SERVICEIt must be required by a MidiDeviceService to ensure that only the system can bind to it
021BIND_NFC_SERVICEBy HostApduService or OffHostApduService, you must ensure that only the system can bind to it
022BIND_NOTIFICATION_LISTENER_SERVICENotification listener service must be required to ensure that only the system can bind to it
023BIND_PRINT_SERVICEprintservice must be required to ensure that only the system can bind to it
024BIND_REMOTEVIEWSThe request must be made through the RemoteViewsService service, which can only be used by the system
025BIND_TELECOM_CONNECTION_SERVICEMust be required by ConnectionService to ensure that only the system can bind to it
026BIND_TEXT_SERVICETextservice (for example, spell checker service) must be required to ensure that only the system can bind to it
027BIND_TV_INPUTThe TvInputService must ensure that only the system can bind to it
028BIND_VOICE_INTERACTIONMust be required by VoiceInteractionService to ensure that only the system can bind to it
029BIND_VPN_SERVICEBinding VPN service must be requested through VpnService service, which can only be used by the system
030BIND_WALLPAPERThe request must be made through the WallpaperService service, which can only be used by the system
031BLUETOOTHAllow programs to connect to paired bluetooth devices
032BLUETOOTH_ADMINAllow programs to discover and pair new Bluetooth devices
033BLUETOOTH_PRIVILEGEDAllows applications to pair bluetooth devices without user interaction. This is not a third-party application available
034BODY_SENSORSAllows the application to access the sensors used by the user to measure what is happening in his / her body, such as a heart rate meter
035BROADCAST_PACKAGE_REMOVEDAllows the program to broadcast a prompt message after an application package has been removed
036BROADCAST_SMSAllows the program to trigger a broadcast when it receives a text message
037BROADCAST_STICKYAllows the program to quickly receive the next broadcast after receiving the broadcast
038BROADCAST_WAP_PUSHThe WAP PUSH service triggers a broadcast after receiving it
039CALL_PHONEAllow programs to make calls from non system dialers
040CALL_PRIVILEGEDAllow the program to make calls and replace the Dialer Interface of the system
041CAMERAAllow the program to access the camera to take photos
042CAPTURE_AUDIO_OUTPUTAllows an application to capture audio output. Not used by third-party applications
043CAPTURE_SECURE_VIDEO_OUTPUTAllows an application to capture video output. Not used by third-party applications
044CAPTURE_VIDEO_OUTPUTAllow an application to capture video output and not be used by third-party applications
045CHANGE_COMPONENT_ENABLED_STATEChange whether the component is enabled
046CHANGE_CONFIGURATIONAllows the current application to change configuration, such as positioning
047CHANGE_NETWORK_STATEAllows the program to change the network state, such as whether it is connected to the network
048CHANGE_WIFI_MULTICAST_STATEAllow programs to change WiFi multicast status
049CHANGE_WIFI_STATEAllow programs to change WiFi status
050CLEAR_APP_CACHEAllows the application to clear the application cache
051CONTROL_LOCATION_UPDATESAllow programs to obtain mobile network location information changes
052DELETE_CACHE_FILESAllow programs to delete cache files
053DELETE_PACKAGESAllow programs to delete apps
054DIAGNOSTICAllow programs to RW to diagnostic resources
055DISABLE_KEYGUARDAllows the program to disable the keyboard lock
056DUMPAllows programs to obtain system dump information from system services
057EXPAND_STATUS_BARAllow programs to expand or shrink the status bar
058FACTORY_TESTAllows the program to run in factory test mode
059FLASHLIGHTAllow access to flash
060GET_ACCOUNTSAllow programs to access account Gmail lists
061GET_ACCOUNTS_PRIVILEGEDAllow access to the list of accounts in the account service
062GET_PACKAGE_SIZEAllow a program to obtain the space occupied by any package
063GET_TASKSAllows a program to obtain information about a currently or recently running task, an abbreviated task status, whether it is active, and so on
064GLOBAL_SEARCHAllow programs to allow global search
065INSTALL_LOCATION_PROVIDERAllow program installation location provider
066INSTALL_PACKAGESAllow applications to install
067INSTALL_SHORTCUTcreate shortcut
068INTERNETAllowing programs to access network connections may generate GPRS traffic
069KILL_BACKGROUND_PROCESSESAllows programs to call killBackgroundProcesses(String) Method to end the background process
070LOCATION_HARDWAREHardware that allows location functionality to be used in an application without third-party applications
071MANAGE_DOCUMENTSAllows an application to manage access to documents, usually a document selector section
072MASTER_CLEARAllows programs to perform soft formatting and delete system configuration information
073MEDIA_CONTENT_CONTROLAllow an application to know what is playing and control its content. Not used by third-party applications
074MODIFY_AUDIO_SETTINGSAllows the program to modify sound setting information
075MODIFY_PHONE_STATEAllows the program to modify the phone status, such as flight mode, but does not include the replacement system Dialer Interface
076MOUNT_FORMAT_FILESYSTEMSAllows programs to format removable file systems, such as formatting and emptying SD cards
077MOUNT_UNMOUNT_FILESYSTEMSAllow programs to mount and unmount external file systems
078NFCAllows the program to perform NFC short-range communication operations for mobile support
079PACKAGE_USAGE_STATSAllows a program to set its activities display
080PERSISTENT_ACTIVITYAllows the program to create a permanent Activity that is marked to be removed in the future
081PROCESS_OUTGOING_CALLSAllow programs to monitor, modify, or abandon broadcast calls
082READ_CALENDARAllows the program to read the user's schedule information
083READ_CALL_LOGRead call records
084READ_CONTACTSAllow programs to access contact address book information
085READ_EXTERNAL_STORAGEThe program can read the files in the external storage space of the device (built-in SDcard and external SDCard), if your App has added "write"_ EXTERNAL_ "Storage" permission, there is no need to add read permission. Write permission already includes read permission
086READ_FRAME_BUFFERAllows the program to read the frame cache for screenshots
087READ_INPUT_STATEAllows the program to read the input status of the current key, which is only used for the system
088READ_LOGSAllow programs to read the underlying system logs
089READ_PHONE_STATEAllow programs to access phone status
090READ_SMSAllow programs to read SMS content
091READ_SYNC_SETTINGSAllow programs to read synchronization settings and Google online synchronization settings
092READ_SYNC_STATSAllow the program to read the synchronization status and get Google online synchronization status
093READ_VOICEMAILAllow applications to read voice mail on the system
094REBOOTAllow programs to restart devices
095RECEIVE_BOOT_COMPLETEDAllow programs to run automatically after startup
096RECEIVE_MMSAllow programs to receive multimedia messages
097RECEIVE_SMSAllow programs to receive text messages
098RECEIVE_WAP_PUSHAllow programs to receive WAP PUSH information
099RECORD_AUDIOA microphone that allows programs to record sound through a phone or headset
100REORDER_TASKSThe Z-axis in the system allows tasks to be reordered
101REQUEST_IGNORE_BATTERY_OPTIMIZATIONSApplications with permissions must use ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS this is a normal permission: an application requests that it will always be granted permission without user approval or seeing it.
102REQUEST_INSTALL_PACKAGESAllow applications to request installation packages. For API greater than 22, you must hold the license to use ACTION_INSTALL_PACKAGE application.
103RESTART_PACKAGESAllow the program to end the task through the restartPackage(String) method, which will be abandoned externally
104SEND_RESPOND_VIA_MESSAGEAllow users to use your app to reply to instant SMS when they call
105SEND_SMSAllow programs to send text messages
106SET_ALARMAllow the program to set alarm reminder
107SET_ALWAYS_FINISHAllows the program to set whether the program always exits in the background
108SET_ANIMATION_SCALEAllows the program to set global animation scaling
109SET_DEBUG_APPAllows programs to set up debugging programs, which are generally used for development
110SET_PREFERRED_APPLICATIONSIt allows the program to set the parameters of the application. It no longer works. For details, see the introduction of addPackageToPreferred(String)
111SET_PROCESS_LIMITAllows programs to set a limit on the maximum number of processes
112SET_TIMEAllow programs to set system time
113SET_TIME_ZONEAllows the program to set the system time zone
114SET_WALLPAPERAllow programs to set desktop wallpaper
115SET_WALLPAPER_HINTSAllow programs to set wallpaper suggestions
116SIGNAL_PERSISTENT_PROCESSESAllows the program to send a permanent process signal
117STATUS_BARAllow programs to open, close, and disable the status bar
118SYSTEM_ALERT_WINDOWAllow programs to display system Windows
119TRANSMIT_IRAllow the use of the device's infrared transmitter, if available
120UNINSTALL_SHORTCUTremove shortcuts
121UPDATE_DEVICE_STATSAllow programs to update device status
122USE_FINGERPRINTAllow applications to use fingerprint hardware
123USE_SIPAllow programs to use SIP Video Services
124VIBRATEAllow program vibration
125WAKE_LOCKAllow the application to run the background process after the phone screen is closed
126WRITE_APN_SETTINGSAllow programs to write network GPRS access point settings
127WRITE_CALENDARAllows the program to write to the schedule, but not read
128WRITE_CALL_LOGAllows the program to write (but not read) the user's contact data
129WRITE_CONTACTSWrite contact, but not read
130WRITE_EXTERNAL_STORAGEAllow programs to write to external storage, such as writing files on SD cards
131WRITE_GSERVICESAllow programs to modify Google service maps
132WRITE_SECURE_SETTINGSAllow applications to read or write security system settings
133WRITE_SETTINGSAllows programs to read or write system settings
134WRITE_SYNC_SETTINGSAllow programs to write synchronization settings
135WRITE_VOICEMAILAllow the application to modify and delete the existing voice mail in the system, which can only be used by the system

Topics: Android Unity