gpt4 book ai didi

java - onActivityResult 的行为不符合预期

转载 作者:行者123 更新时间:2023-12-02 08:38:59 27 4
gpt4 key购买 nike

我有一个选择图像的 Intent (我在 fragment 中调用它):

 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/png");
intent.addCategory(Intent.CATEGORY_OPENABLE);
String[] mimetypes = {"image/png","image/jpg", "image/bmp", "image/gif"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", "image/png");
sIntent.addCategory(Intent.CATEGORY_DEFAULT);

Intent chooserIntent;
if (getContext().getPackageManager().resolveActivity(sIntent, 0) != null){
// it is device with Samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
} else {
chooserIntent = Intent.createChooser(intent, "Open file");
}

try {
startActivityForResult(chooserIntent, 548);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
}

在我的 Activity 中:

    @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: request code: " + requestCode);
Log.d(TAG, "onActivityResult: result: " + resultCode + " Success = " + (resultCode == RESULT_OK));
if (requestCode == 548 && resultCode == RESULT_OK) {
Uri uri = data.getData();
Log.d(TAG, "onActivityResult: URI: " + uri.toString());
Log.d(TAG, "onActivityResult: OK");

}
}

输出:onActivityResult:请求代码:66084onActivityResult:结果:-1 成功 = true

如您所见,结果成功,但请求代码发生了变化。所以我无法检查请求是什么。

最佳答案

您的 startActivityForResult() 调用应该与您的 onActivityResult() 处于同一位置。

因此,如果您希望 onActivityResult() 位于 Activity 上,请在 Activity 上调用 startActivityForResult()

fragment 上的

startActivityForResult() 有意更改 requestCode 以尽量减少与其他 startActivityForResult() 调用的冲突,特别是在其他 fragment 上进行的调用在同一个 Activity 中。

关于java - onActivityResult 的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61501846/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com