The first line of code Chapter 7-Explore the content provider

7.1 Introduction to Content Provider

Content Provider (Content Provider) is mainly used to realize the function of data sharing between different applications. It provides a complete mechanism that allows one program to access data in another program, while also ensuring the security of the accessed data.

The content provider can choose only which part of the data to share, so as to ensure that there is no risk of leakage of the private data in our program.

7.2 Run permissions

Android 6.0 refers to the runtime permission function, which well protects the security and privacy of users.

7.2.1 Detailed explanation of Android permission mechanism

Android requires us to add corresponding permissions in AndroidManifest.xml when accessing users involves security. In this way, the user is protected in the following two aspects

在低于6.0的系统设备上安装程序时,就会在安装界面提醒用户该apk需要的权限
用户可以在应用程序管理界面查看任意一个程序的权限申请情况

However, many commonly-used software has "shop bullying" and abuses many permissions. Therefore, the Android R&D team added the runtime permission function in 6.0. That is, the user does not need to authorize all the requested permissions at one time when installing the software, but can authorize a certain permission request during the use of the software.
Of course, not all permissions are applied at runtime.

● Ordinary authority
● Dangerous authority
Ordinary authority : refers to the authority that will not threaten the safety and privacy of the user, and the system will automatically authorize it for us.
Dangerous permissions : refer to permissions that may touch user privacy or affect device security. The user must manually click on authorization, otherwise the program will not be able to use the corresponding functions.
The dangerous permissions in Android are mainly as follows:
Insert picture description here
Note: Each permission in the table belongs to a permission group, and the permission name is used when handling runtime permissions. Once the user agrees to the authorization, then the permission group corresponding to the permission All other permissions will also be authorized at the same time.

Click to view all permissions in the Android system

7.2.2 Apply for permission while the program is running

android application permission API:
1.checkSelfPermission to check whether the permission is allowed
2 requestPermissions request one or several permissions
3.onRequestPermissionsResult call back the result after manually requesting permission
4.shouldShowRequestPermissionRationale "not asking"

Pay special attention to shouldShowRequestPermissionRationale:

1.第一次用户没有请求权限    false
2.用户第一次请求了权限 拒绝true  允许 false
3.用户再次请求 显示不在询问  点击不在询问 拒绝 false  点击不在询问允许false

只有当用户选择不在提醒拒绝是返回false 

Explanation:
Step 1 : Determine whether the user has authorized us.
Use the checkSelfPermission() method to determine whether the user has authorized. A total of two parameters are received:

   参数一:上下文
   参数二:具体的权限名     Manifest.permission.xxxxx

Step 2 : Compare the returned value with PackageManager.PERMISSION_GRANTED. If it is equal, it means that the user has been authorized, and if it is not equal, it means that the user is not authorized.

Step 3 : If there is no authorization, call the requestPermissions() method to apply for authorization from the user. requestPermissions() receives three parameters:

参数一:Activity实例
参数二:String数组,把要申请的权限名放在数组中
参数三:请求码,只要确保是唯一值就行

**Step 4:** Judge the authorization result. Judge
whether the user has "click not to ask", click it and jump to the setting screen to manually open the permissions.
Note: When the user launches the apk for the first time, request permission If it is "Not Asking", it will not be displayed. It will only be displayed in future permission requests. When the user clicks "Not Asking", it will return false

For example:
click the button permission request

public class MainActivity extends AppCompatActivity {
    
    

    private static final String  TAG = "permission";
    private String[] perm = {
    
    
            Manifest.permission.ACCESS_COARSE_LOCATION,  //定位权限
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG,"onCreate");
    }
    public void Call(View view) {
    
    
        switch (view.getId()) {
    
    
            case R.id.button:
                CheckPermission(perm);
                break;
            case R.id.button1:
                break;
        }
    }
    public void CheckPermission(String []  perm) {
    
    
        //1.首先检查有没有权限
        //2.在请求权限
        //3.

        if (Build.VERSION.SDK_INT>23 && this.getApplicationInfo().targetSdkVersion>23) {
    
    
            List<String> denpermis = new ArrayList<>();
            for (String string:perm) {
    
    
                int result = this.checkSelfPermission(string);
                if (result!= PackageManager.PERMISSION_GRANTED) {
    
    
                    denpermis.add(string);
                }
            }
            if (denpermis.size()!=0) {
    
    
                String[] strings = denpermis.toArray(new String[denpermis.size()]);
                this.requestPermissions(strings,0);
            }
        }
    }

    //权限结果
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    
    
        Log.d(TAG,"onRequestPermissionsResult:"+requestCode+" "+permissions.length+" "+ Arrays.toString(grantResults));
        for (int i=0;i<grantResults.length;i++) {
    
    
                if (grantResults[i]!=PackageManager.PERMISSION_GRANTED) {
    
    //没有点击允许

                    boolean is = this.shouldShowRequestPermissionRationale(permissions[i]);  //第一次进入是默认是false 以后都是true
                    if (is) {
    
    
                        Log.d(TAG,"true");
                    }else {
    
    
                        //点击了不在询问 手动 跳转到设置界面
                        Log.d(TAG,"false");
                        showMissingPermissionDialog();
                        break;

                    }
                }
        }
    }
private void showMissingPermissionDialog() {
    
    //如果权限没有获取,弹窗显示
        try{
    
    
            Log.d(TAG,   "showMissingPermissionDialog   ");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("当前应用缺少必要权限。\\n\\n请点击\\\"设置\\\"-\\\"权限\\\"-打开所需权限");

            // 拒绝, 退出应用
            builder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    
                            try{
    
    
                                finish();
                            } catch (Throwable e) {
    
    
                                e.printStackTrace();
                            }
                        }
                    });
            //进入设置,设置权限
            builder.setPositiveButton("设置",
                    new DialogInterface.OnClickListener() {
    
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
    
    
                            try {
    
    
                                startAppSettings();//启动设置
                            } catch (Throwable e) {
    
    
                                e.printStackTrace();
                            }
                        }
                    });

            builder.setCancelable(false);

            builder.show();
        }catch(Throwable e){
    
    
            e.printStackTrace();
        }
    }
    private void startAppSettings() {
    
    
        try{
    
    
            Log.d(TAG,   "startAppSettings  begin ");
            Intent intent = new Intent(
                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            Log.d(TAG,   "startActivity   end");
        } catch (Throwable e) {
    
    
            e.printStackTrace();
        }
    }
}

7.3 Access to data in other programs

There are two main uses of content providers :

  1. Use existing content providers to read and manipulate data in the corresponding program
  2. Create your own content provider to provide external access to the data of our program

If an application provides an external access interface to its data through the content provider, then any other application can access this part of the data. The phone book, SMS, media library, and other programs that come with the Android system are all Provides a similar interface, which allows third-party applications to make full use of this part of the data to achieve better functions.

7.3.1 Basic usage of ContentResolver

Guess you like

Origin blog.csdn.net/weixin_41477306/article/details/105933249