我试图将一个文件保存为
PNG
一个画布,用户可以在上面画东西,然后调用
Intent.ACTION_SEND
,这样用户就可以与其他应用程序分享它的画。
代码能够顺利保存文件,但当我试图使用
MediaScannerConnection.scanFile()
时,函数返回的
Uri
是
null
。我使用的是创建文件的绝对路径,所以我不明白为什么会发生这种情况。
我的类,叫做
BitmapAsyncTask
,继承自
AsyncTask
(是的,我知道它已经废弃了)。下面是重要的代码。
Writing the file to memory:
override fun doInBackground(vararg p0: Any?): String {
var result = ""
try {
val bytes = ByteArrayOutputStream()
mBitmap.compress(Bitmap.CompressFormat.PNG, 95, bytes)
val file = File(externalCacheDir!!.absoluteFile.toString()
+ File.separator + "KidsDrawingApp_"
+ System.currentTimeMillis() / 1000 + ".png")
val fileOutput = FileOutputStream(file)
fileOutput.write(bytes.toByteArray())
fileOutput.close()
result = file.absolutePath
} catch (e: Exception) {
e.printStackTrace()
Log.d("File", result)
return result
** mBitmap
变量只是从画布上生成的Bitmap。
在此,以Log.d
为例,返回。
D/File: /storage/emulated/0/Android/data/com.example.kidsdrawingapp/cache/KidsDrawingApp_1599992654.png
如果我打开Files
应用程序并搜索该文件,我就可以正常访问该文件。
但当我在MediaScannerConnection
上运行onPostExecute()
时,该函数根本没有返回一个基于绝对路径的URI。下面是代码。
MediaScannerConnection.scanFile(this@MainActivity, arrayOf(result), null) {
path, uri -> val shareIntent = Intent()
Log.d("Path", path)
Log.d("Uri", uri.toString())
shareIntent.action = Intent.ACTION_SEND
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
shareIntent.type = "image/png"
startActivity(
Intent.createChooser(
shareIntent, "Share image"
再一次,Log.d("Path", path)
返回的文件与之前的Log.d()
相同,但是当我试图将Uri
转换成字符串时,它崩溃了,因为它是空的。
我试着像在其他一些答案中看到的那样加入"file://" + file.absolutePath"
,但还是不行,由scanFile()
返回的uri
仍然是空的。
我正在使用API 21。
File Provider Code
AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.kidsdrawingapp.fileprovider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/path" />
</provider>
@xml/path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="captured" path="Android/data/com.example.kidsdrawingapp/files" />
</paths>