0

我想在 AppA 中创建一个文件,然后只能从 AppB 访问它。我可以通过 DocumentProvider 创建文件,然后通过 StorageClient 访问它,请参见此处的示例。如何在 AppA 中设置文件的权限,以便只有 AppB 可以访问它?

AppA中的文件创建方法

        String s = "kv;ab\nkv1;cd";
        try {
            byte[] buffer = s.getBytes();
            String filename = "myfile.txt";
            System.out.println("filename="+filename);
            FileOutputStream fos = getContext().openFileOutput(filename, Context.MODE_PRIVATE);
            fos.write(buffer);
            fos.close();
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }   

AppB中的文件访问方法

public void onClick(View view) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("text/plain");
        Uri pickerInitialUri= Uri.parse("content://com.example.android.storageprovider.documents/document/root%3Amyfile.txt");
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
        startActivityForResult(intent, READ_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);
        readFileExternalStorage();
    }

    public String readFileExternalStorage() {
        String s = "";
        Uri uri1 = Uri.parse("content://com.example.android.storageprovider.documents/document/root%3Amyfile.txt");
        try {
            InputStream ins = this.getBaseContext().getContentResolver().openInputStream(uri1);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            int size;
            byte[] buffer = new byte[1024];
            while ((size = ins.read(buffer, 0, 1024)) >= 0) {
                outputStream.write(buffer, 0, size);
            }
            ins.close();
            buffer = outputStream.toByteArray();
            s = new String(buffer);
            System.out.println("output=" + s);
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        TextView textview = findViewById(R.id.textView);
        textview.setText(s);
        return "ok\n" + s;
    }
4

1 回答 1

0

两种可能的选择——

  1. https://developer.android.com/guide/topics/permissions/defining

  2. 使用基于用户的 salt 的共享加密密钥来加密和解密 Android 上存储的文件

于 2021-04-30T04:36:11.697 回答