I want to create a file in AppA and then be able to access it from AppB only. I am able to create the file via the DocumentProvider and then access it via StorageClient see examples here. How do I setup the permission on the file in AppA so that only AppB can access it?
Method for file creation in 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();
}
}
Methods for File access in 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;
}
Two probable options-
https://developer.android.com/guide/topics/permissions/defining
Use a shared encryption key with user based salt to encrypt and decrypt stored files on Android