Android 7 steps to request/share a file to another app
2 min readJun 6, 2020
Step 1: Request a file from appB
requestFileIntent = Intent(Intent.ACTION_PICK).apply {
type = "image/png"
}startActivityForResult(requestFileIntent, 0)
Step 2: Get result
returnIntent?.data?.also { returnUri ->
my_photo.setImageURI(returnUri) val mimeType: String? = returnIntent.data?.let { returnUri ->
contentResolver.getType(returnUri)
}}
Copy file
private lateinit var inputPFD: ParcelFileDescriptorinputPFD = try {
contentResolver.openFileDescriptor(returnUri, "r") ?: kotlin.run { return }
} catch (e: FileNotFoundException) {
e.printStackTrace()
Log.e("MainActivity", "File not found.")
return
}
FileInputStream(inputPFD.fileDescriptor).use { _in ->
FileOutputStream(File(filesDir,"youFile.png")).use { _out ->
try {
val buff = ByteArray(1024)
var read = 0
while (_in.read(buff).also { read = it } > 0) {
_out.write(buff, 0, read)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
Sharing a file from appA
The only secure way: send file’s content URI and grant temporary access permissions to that URI.
Step 1: Specify the FileProvider in appA
- add res/xml/filepaths.xml
- add provider in manifest.xml
<paths>
element can have multiple children, each specifying a different directory to share. <files-path>
shares directories within the files/
directory of your app's internal storage. <external-path>
element to share directories in external storage, and the <cache-path>
element to share directories in your internal cache directory.
Step 2: Add intent-filter in your provider activity
<action android:name="android.intent.action.PICK"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.OPENABLE"/>
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*"/>
Step 3: Make content URI
FileProvider.getUriForFile(
this@MainActivity,
"nj.f.njsharefile.fileprovider",
imagePath)
Step 4: Grant permission and return the result
resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
resultIntent.setDataAndType(fileUri, contentResolver.getType(fileUri))
setResult(Activity.RESULT_OK, resultIntent)