我正在使用仿真器,并以这种方式发送意图:
StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
Intent i;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
i = sm.getPrimaryStorageVolume().createOpenDocumentTreeIntent();
} else {
return null;
}
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
i.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
和onActivityResult()
中的
Uri uri = data.getData();
if (uri == null)
return null;
context.getContentResolver()
.takePersistableUriPermission(uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
每次我重新启动时,该应用都无权访问。谁能在模拟器的Beta 6上确认此错误?我做错什么了吗?
答案 0 :(得分:1)
我将您的代码段转换为Kotlin活动:
package com.commonsware.jetpack.myapplication
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import android.os.storage.StorageManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.documentfile.provider.DocumentFile
private const val PREF_URI = "uri"
private const val REQUEST_SAF = 1337
class MainActivity : AppCompatActivity() {
private val prefs: SharedPreferences by lazy {
getSharedPreferences("test", Context.MODE_PRIVATE)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val uriString = prefs.getString(PREF_URI, null)
val storageManager = getSystemService(StorageManager::class.java)!!
if (uriString == null) {
startActivityForResult(
storageManager.primaryStorageVolume.createOpenDocumentTreeIntent(),
REQUEST_SAF
)
} else {
val uri = Uri.parse(uriString)
val docFile = DocumentFile.fromTreeUri(this, uri)
Toast.makeText(
this,
"canRead: ${docFile?.canRead()} canWrite: ${docFile?.canWrite()}",
Toast.LENGTH_LONG
).show()
}
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
val uri = data?.data
if (uri == null) {
Toast.makeText(this, "Did not get a Uri??!?", Toast.LENGTH_LONG).show()
} else {
contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
prefs.edit().putString(PREF_URI, uri.toString()).apply()
Toast.makeText(this, "OK, run the activity again", Toast.LENGTH_LONG).show()
}
finish()
}
}
然后我运行包含此活动作为其启动器活动的应用程序,并选择Downloads/
作为文档树。此活动的后续启动-在重新启动之前和之后-显示canRead()
和canWrite()
均返回true
。已在运行Q Beta 6的Google Pixel上进行了测试。
我无法在Q仿真器because Google上尝试此操作,因此无法确认是否可以在此处重现您的行为。但是,这在硬件上可以按预期工作的事实应该是一个积极的信号。