Не удается открыть файл из намерения в Android 10 - PullRequest
0 голосов
/ 20 июня 2020

Я пытаюсь получить доступ к файлу из Intent.ACTION_GET_CONTENT, когда я пробую его на своем устройстве (это Android 8), он работает отлично. Но потом, когда я пробую его на устройстве своих друзей (Android 10), он не работает. Когда я пытаюсь открыть файл из Word, он продолжает говорить: «Не могу открыть файл. Попробуйте сохранить файл на устройстве, а затем открыть его». И когда я открываю файл pdf, он ничего не показывает, только черный экран.

btn_add OnClick Listener

        btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String[] mimeTypes = {"application/vnd.google-apps.document", "application/pdf", "application/vnd.google-apps.form",
                    "application/vnd.google-apps.presentation", "application/vnd.google-apps.spreadsheet",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "application/x-excel"};
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
                if (mimeTypes.length > 0) {
                    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                }
            } else {
                String mimeTypesStr = "";

                for (String mimeType : mimeTypes) {
                    mimeTypesStr += mimeType + "|";
                }
                intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
            }                startActivityForResult(intent, 100);
        }
    });

onActivityResult

                titleArrays = new ArrayList<>();
                ItemAdapter adapter = new ItemAdapter(titleArrays);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(adapter);
                Log.d("Id: ", ""+id);

                hashMap.put(id, data.getData());
                returnCursor =
                        getContentResolver().query(data.getData(), null, null, null, null);
                nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                returnCursor.moveToFirst();
                titleHashmap.put(id, returnCursor.getString(nameIndex));
                for (int i : hashMap.keySet()){
                    titleArrays.add(new ItemProperty(hashMap.get(i), titleHashmap.get(i)));
                }
                img_file.setImageResource(0);

                id++;
                // Item OnClick
                adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Log.d("Position: ", ""+position);
                        Intent intent = new Intent(Intent.ACTION_VIEW, titleArrays.get(position).getUri());
                        startActivity(intent);
                    }
                });

Интересно, что я сделал неправильно. Если вы знаете это, дайте мне знать. Спасибо!

1 Ответ

0 голосов
/ 20 июня 2020

Итак, я наконец решил это, выполнив инструкцию CommonsWare ! Я добавил Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION в свой Action_VIEW Intent и изменил ACTION_GET_CONTENT на ACTION_OPEN_DOCUMENT

*

btn_add OnClick Listener

    String[] mimeTypes = {"application/vnd.google-apps.document", "application/pdf", "application/vnd.google-apps.form",
                    "application/vnd.google-apps.presentation", "application/vnd.google-apps.spreadsheet",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "application/x-excel"};
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
                if (mimeTypes.length > 0) {
                    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                }
            } else {
                String mimeTypesStr = "";

                for (String mimeType : mimeTypes) {
                    mimeTypesStr += mimeType + "|";
                }
                intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
            }
            startActivityForResult(intent, 100);

onActivityResult

if (resultCode == RESULT_OK) {
                titleArrays = new ArrayList<>();
                ItemAdapter adapter = new ItemAdapter(titleArrays);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(adapter);
                Log.d("Id: ", ""+id);

                hashMap.put(id, data.getData());
                returnCursor =
                        getContentResolver().query(data.getData(), null, null, null, null);
                nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                returnCursor.moveToFirst();
                titleHashmap.put(id, returnCursor.getString(nameIndex));
                for (int i : hashMap.keySet()){
                    titleArrays.add(new ItemProperty(hashMap.get(i), titleHashmap.get(i)));
                }
                img_file.setImageResource(0);

                id++;
                // Item OnClick
                adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Log.d("Position: ", ""+position);
                        Intent intent = new Intent(Intent.ACTION_VIEW, titleArrays.get(position).getUri());
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        startActivity(intent);
                    }
                });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...