[英]Passing data through intent for onActivityResult
我試圖在用戶選擇的位置保存一個 pdf 文件,但我在通過意圖傳遞數據時遇到了問題。
我嘗試使用包來傳遞信息,但它始終是 null。只有在我添加局部變量並在 @save 方法中分配它時它才有效。 但我想通過意圖傳遞它。
事情是我不會進入另一個活動,只是選擇一個目錄然后我回來。
`protected void save(byte[] bytes, String fileName, String mimeType) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.setType(mimeType);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_TITLE, fileName);
intent.putExtra("bytes", bytes);
activityResultLaunch.launch(intent);
}`
`ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
Intent data = result.getData();
try {
Uri uri = data.getData();
OutputStream outputStream = getContext().getContentResolver().openOutputStream(uri);
// here it is always null
//byte[] bytes = data.getByteArrayExtra("bytes");
outputStream.write(bytes);
outputStream.close();
Toast.makeText(getContext(), "Successfully saved document to device!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getContext(), "Failed to save document to device.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});`
有什么建議么? 我看不出我在這里缺少什么,我已經為此苦苦思索了幾個小時,卻無法讓它發揮作用。 任何幫助是極大的贊賞!
intent.putExtra("bytes", bytes);
在這里,您將Intent
extra 傳遞給您正在啟動的活動。 該活動是響應ACTION_CREATE_DOCUMENT
的設備提供的活動。
更重要的是,這不是您的活動。 肯定不是為該Intent
調用launch()
的活動。
因此,額外的bytes
將可用於ACTION_OPEN_DOCUMENT
活動。 該活動將忽略該額外內容。 它不會在傳遞給您的onActivityResult()
方法的完全不同的Intent
中包含該額外內容。
但我想通過意圖傳遞它。
抱歉,這不是 Android 中的選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.