我的活动需要从文档提供者处请求新文档。
我想通过将活动结果与uri相结合来在我的espresso测试中测试这个。但是,返回的uri没有授予正确的权限。当我尝试SecurityException: No persistable permission grants found for [user] and [uri]
takePersistableUriPermission
onActivityResult中我的活动的相关代码:
val takeFlags = data.getFlags() and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
contentResolver.takePersistableUriPermission(it, takeFlags)
espresso测试的相关代码
val file = File(InstrumentationRegistry.getTargetContext().filesDir, "abc.txt2)
val uri = Uri.parse("file://" + file.absoluteFile)
Intents.intending(hasAction(Intent.ACTION_CREATE_DOCUMENT))
.respondWith(Instrumentation.ActivityResult(RESULT_OK, Intent().setData(uri)))
<click on button to request document>
如何使用授予权限的uri来调用活动结果?
答案 0 :(得分:0)
使用
val uri = Uri.fromFile(file)
代替
val uri = Uri.parse("file://" + file.absoluteFile)
别忘了提供许可
@get:Rule
var permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
android.Manifest.permission.READ_EXTERNAL_STORAGE
)
适用于我的情况
答案 1 :(得分:0)
以下代码对我来说效果很好
val intent = TestGeneralUtil.genIntentWithPersistedReadPermissionForFile(att)
intending(
allOf(
hasAction(Intent.ACTION_CHOOSER),
hasExtra(`is`(Intent.EXTRA_INTENT),
allOf(
hasAction(Intent.ACTION_OPEN_DOCUMENT),
hasType("*/*"),
hasCategories(hasItem(equalTo(Intent.CATEGORY_OPENABLE)))
)
)
)
).respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, intent))
和
/**
* Generate an [Intent] with [Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION]
* and [Intent.FLAG_GRANT_READ_URI_PERMISSION]
*/
fun genIntentWithPersistedReadPermissionForFile(file: File): Intent {
return Intent().apply {
val context: Context = ApplicationProvider.getApplicationContext()
val uri = FileProvider.getUriForFile(context, Constants.FILE_PROVIDER_AUTHORITY, file)
context.grantUriPermission(
BuildConfig.APPLICATION_ID,
uri,
Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
data = uri
flags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
}
}