Android Studio:无法在 EditText 中打开 .txt 文件 - 不断出现权限拒绝错误

问题描述 投票:0回答:1

在我的 Android 应用程序中

Song_Tracker
我希望打开
txt
我从笔记本电脑复制过来的文件 - 文件存储在
\Internal storage\DCIM\sheet_music
目录中,当我解析目录并加载文件名时,我也会加载文件
 URI
。我希望将
txt
文件打开到 EditText 字段中,以便用户可以查看或编辑/保存。我将
txt
文件名存储在我的 SQLite 数据库中,最终希望从一首歌曲滑动到下一首,每首歌曲都加载到 RecycleView 中。

这是我收到的错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.enetapplications.songtracker/com.enetapplications.songtracker.editsong.NewEditSongActivity}: java.lang.SecurityException: 
Permission Denial: opening provider com.android.externalstorage.ExternalStorageProvider from ProcessRecord{f235d79 11381:com.enetapplications.songtracker/u0a540} 
(pid=11381, uid=10540) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

我已在

Manifest
中设置权限如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...

我尝试过使用

ACTION_OPEN_DOCUMENT
但是这会打开一个我不想要的文件选择器 - 我希望简单地单击或从一个
txt
文件滑动到下一个文件,而无需转到每个文件的文件选择器。

这里是

.class
,它正在打开包含来自 here 的提示的文件。该代码似乎运行正常,但我无法判断,因为我不断收到“权限拒绝”错误。我尝试在下面的代码中使用
requestPermissionLauncher
但出现同样的错误。我已经尝试过
ContextCompat.checkSelfPermission
仍然是同样的错误。

package com.enetapplications.songtracker.editsong;

import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.enetapplications.songtracker.R;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class NewEditSongActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 123; // Define your own request code

    EditText editTextSongContent;
    TextView textViewSongName;
    Uri songUri; // Storing URI to be accessible throughout the class

    private ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
        if (isGranted) {
            // Permission is granted, proceed to open the file
            openFile(songUri);
        } else {
            // Permission denied, handle this situation (e.g., show a message or adjust app behavior)
            // For instance: showToast("Permission denied. Cannot open the file.");
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_edit_song);

        editTextSongContent = findViewById(R.id.editTextSongContent);
        textViewSongName = findViewById(R.id.textViewSongName);

        // Get the URI of the file to open
        String uriString = getIntent().getStringExtra("song_uri");
        if (uriString != null) {
            songUri = Uri.parse(uriString);

            // Check for READ_EXTERNAL_STORAGE permission
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted, proceed to open the file
                openFile(songUri);
            } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // Explain why your app requires this permission and what features are disabled if declined
                // An educational UI should be shown to the user
                // For instance: showInContextUI("Explanation for access to external storage");
            } else {
                // Request permission using the ActivityResultLauncher
                requestPermissionLauncher.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        }
    }

    private void openFile(Uri uri) {
        // Open the file and read its contents
        InputStream inputStream = null;
        try {
            inputStream = getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while (true) {
            try {
                if ((line = reader.readLine()) == null) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            editTextSongContent.append(line);
        }

        // Close the file
        try {
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

java android android-edittext txt
1个回答
0
投票

我无法发表评论,所以我就留在这里 据我了解,您需要控制所有系统文件,如果是这样,请尝试

 MANAGE_EXTERNAL_STORAGE

请注意,这是一个高风险的解决方案。 Google 控制台网站上也有关于此的官方文档 网站

© www.soinside.com 2019 - 2024. All rights reserved.