Learning practice of Android permission application

1. Introduction

Before switching to an Android phone, the impression of the Android system is the racetrack of the system app. The app can ask for various permissions at will and steal various privacy at will. After changing the mobile phone, it is known that the Android system has a great management of permissions In other words, every dangerous permission requested requires prompting the user. Of course, Android only prompts the user as much as possible. There are still cases where the user does not agree to use it.

The improvement of permission management adds a certain amount of work to developers. Applying for dangerous permissions is no longer a simple matter of adding a line of code in AndroidManifest.xml, but the need to prompt users to apply dynamically. After understanding the dynamic application, I do n’t think it ’s too complicated, but when I do n’t know, I only know how to copy the ready-made code fragments online, and I do n’t know where to start when I need to apply for new permissions. I once pasted a few pieces of dynamic application permission code, just because I do n’t understand the principle, I only copy and paste it. Although the code can run, it is extremely bloated.

To this end, through this article to sort out Android permissions, in order to master Android permissions management, refused to be a Copy engineer.

2. The role of authority

The purpose of permissions is to protect the privacy of Android users. As an open source system that can be customized arbitrarily, permissions are really the last barrier to user privacy. The Android system requires that, by default, no application has the right to perform any operations that would adversely affect other applications, operating systems, or users. Including reading and writing user's private data (such as contacts or e-mail), reading and writing files of other applications, accessing the network and so on. To perform these operations, the Android application must obtain the corresponding permissions.

Android has hundreds of permissions, which can be divided into three categories, one is ordinary permissions, the other is signature permissions, and the other is dangerous permissions.

Among them, ordinary permissions refer to those that do not threaten the security and privacy of users, such as setting alarm clock permissions. Granting normal permissions for the app only needs to be declared in the AndroidManifest.xml file, the system will automatically authorize, no user confirmation is required, and the user cannot do the revocation operation.

The second type is the signing permission. This type of permission is also granted by the system when the application is installed, but it is not granted unconditionally. The application that wants to use the permission must use the same certificate as the application that defines the permission. For example, application A Signing with certificate A defines a signing permission. Application B wants to use this permission and must be signed by certificate A. The scenario where signature permissions are used is such that a company has multiple apps. In order to allow these apps to call each other, but do not want to be called by external apps, you can implement a custom signature call permission.

Finally, let ’s look at the third type of dangerous permissions. The reason why dangerous permissions are dangerous is because such permissions involve the user ’s personal sensitive data resources, or affect the user ’s stored data or other application data, such as reading user contacts and opening There have been rumors on microphones, etc. At present, many apps will secretly open the microphone to eavesdrop on the user's conversation, and then accurately push the advertisement according to the content of the conversation. Such rumors are like urban legends. Because of the mysterious performance, they are widely spread. In order to obtain dangerous permissions, an application must prompt the user that the application cannot obtain permissions until the user permits. However, the Android system is open source after all. It is possible to modify the native Android permission management function. Although the user did not agree, the app can still obtain permissions. This topic is beyond the scope of this article. Personally think that there are other better ways to steal privacy Eavesdropping on conversations is the kind of higher cost, not worth using.

As mentioned earlier, there are hundreds of permissions, and it is unrealistic to remember one by one. In fact, as long as we know which are dangerous permissions, the dangerous permissions are ordinary permissions.

Dangerous permissions are divided into 9 groups in total and 24 permissions. If the permissions we applied for are not in this table, it means that they are ordinary permissions, and permission grouping means that these permissions in the group belong to the same group, and the user agrees to authorize a permission group. Then all the permissions in the group will be granted. For example, after the application is granted the READ_EXTERNAL_STORAGE permission, if you apply for the WRITE_EXTERNAL_STORAGE permission again, the system will grant the permission immediately and no longer prompt the user.
Insert picture description here

3. Steps and examples for applying for permission

  1. Applying for normal permissions is simple, just apply in the AndroidManifest.xml file, for example, apply for permission to set the alarm
<uses-permission android:name="android.permission.SET_ALARM" />
  1. Signing permission application is similar, only need to modify protectionLevel into signature, for example, set a custom permission into signature permission, the code is as follows, other applications must have the same signature to grant this permission to grant
    <permission
     android:name="com.test.permission.act"
     android:protectionLevel="signature"/>
    
  2. Important point to apply for dangerous permissions. On the one hand, like ordinary permissions, it still needs to be declared in the AndroidManifest.xml file. On the other hand, additional dynamic applications are required. The following uses the application of storage read and write permissions as an example.
  • Declared in the AndroidManifest file, this step is essential

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    • Check the permissions in the application startup code to confirm whether the application already has read and write storage permissions. This part is implemented in the code, so it is called dynamic application. Use Android in ContextCompat.checkSelfPermission()check authorization rights, this method first parameter is the context Context, the second parameter is the name you want to apply for permission, of course, can not just write the name of Tun Town, but there is a specific name, the proposal directly tune in Android Manifest.permissionhas been The defined name, for example, the read external storage permission to be applied for now is Manifest.permission.WRITE_EXTERNAL_STORAGE. This method returns an int type PERMISSION_GRANTED(同意)or PERMISSION_DENIED`(拒绝). Generally speaking, after the program is installed for the first time, the requested permissions are all in the PERMISSION_DENIEDstate. You need to apply for it. You do not need to apply again after the user agrees, unless you uninstall the application and reinstall it or turn off the permissions in the system settings;

    • The next step is to apply for permission. requestPermissions()The method used for applying. There are three parameters passed in this method. The first is Activity and the second is an array of permission strings that require authorization. You can include the names of the permissions you want to apply for. The third is the request code that identifies the permission request. It is used in the callback function for permission application onRequestPermissionsResult(). This value must be greater than or equal to 0. Its role will be described in detail in the callback function. Here, as long as it is understood as a custom tag. It should be noted that the application for permission is processed asynchronously, that is, the code will not block waiting for the user to click, but the callback after the user clicks onRequestPermissionsResult(). The code for the above two steps is as follows:

 //检查应用是否已经拥有权限
 if(ActivityCompat.checkSelfPermission(MainActivity.this,
               Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
           // 说明没有该权限,就需要申请权限
           ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
       }else {
           //已经拥有权限,做进一步操作
       }
  • Next is to overwrite the application permission callback function onRequestPermissionsResult(), and do follow-up processing for the permission application. The callback function has three return results. The first one requestCode, this parameter is requestPermissions()the request code for identifying the permission mentioned, the function is a receipt number, according to We can determine the result of the processing of the order number, that is, pass this parameter when applying for the permission. After the processing is completed, the callback function will be returned unchanged, so that we know whether it is our processing result. ; The second parameter is the permission string array, which is requestPermissions()the permission string array we are filling; the third parameter is the user response array, the user's approval of each application for permission is in this array, this array The number is one-to-one correspondence with the application permission array. code show as below:
  @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
                //通过requestCode来识别是否同一个请求
        if (requestCode == 1){
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //用户同意执行的操作
                
            }else{
                //用户不同意不同意执行的操作,例如提示用户不同意不给用。。。
            }
        }
    }

If you apply for a single authority above, what if you apply for multiple authorities? The basic steps are similar to applying for a single permission, but because it is multiple permissions, additional processing is required, such as how to determine whether each permission is authorized. Let ’s apply for one more recording permission

  • Similarly, first make a declaration in AndroidManifest.xml
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
  • The preparation is to create an array of permission strings and declare a list of permissions, where the list is used to determine the processing status of each permission
    String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();
    
    • Judging the authorization status of each authority, and adding it to the application list without consent, then applying for authority
    private void myRequestPermission() {
        mPermissionList.clear();
        //逐个判断权限是否已经通过
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {            
                //如果未授权,则添加到列表中
                mPermissionList.add(permissions[i]);
            }
        }

        //申请权限,如果列表不为空,说明有权限需要申请
        if (mPermissionList.size() > 0) {
            //有权限没有通过,需要申请
            ActivityCompat.requestPermissions(this, permissionsList.toArray(new String[permissionsList.size()]), 1);
        }else{
            //已有权限,做进一步操作
    }
    }
  • Overwrite the method of requesting permission callback for subsequent processing
 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                int resultLength = grantResults.length;
                //说明回调成功了,权限授权被允许
                if(resultLength > 0){
                    for(int grantCode : grantResults){
                        if(grantCode == PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                break;
                default:
                    break;
        }
    }

4. Summary

After understanding Android permissions, it can be seen that the process of applying for permissions is not very complicated, ordinary permissions are relatively simple, only need to be declared in AndroidManifest.xml, dangerous permissions need not only be declared in AndroidManifest.xml, but also need to dynamically apply in the code , The first is to checkSelfPermission()check whether a dangerous permission is authorized, if not authorized, requestPermissions()apply for authorization, remember that this is asynchronous processing, the code will not block waiting for the user to authorize the position, the next step is to handle the authorization situation, the system callback onRequestPermissionsResultinforms us to deal with As a result, we do further processing based on this result. Applying for multiple permissions at the same time is a bit more complicated, and needs to handle the processing of each permission.

Published 19 original articles · praised 6 · visits 6432

Guess you like

Origin blog.csdn.net/lansoul1987/article/details/105602076