Не удается получить разрешение на копирование файла в SDCard из папки активов - PullRequest
0 голосов
/ 22 февраля 2019

В Android я создаю следующую программу

MainActivity.java

    public class MainActivity extends AppCompatActivity {

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

        TextView tvContent = (TextView) findViewById(R.id.tvContent);

        try {
            InputStream file = getResources().getAssets().open("hello.txt");


            if (file != null) {

                Toast.makeText(this, "File Exists", Toast.LENGTH_LONG).show();

                String mytext = "";

                while (file.available() > 0) {
                    mytext = mytext + (char) file.read();
                }

                //tvContent.setText("path: " + Environment.getExternalStorageDirectory() + "/hello.txt");

                tvContent.setText("path: " + System.getenv("SECONDARY_STORAGE") + "/hello.txt");

                byte b[] = mytext.getBytes();

                //OutputStream os = new FileOutputStream(Environment.getExternalStorageDirectory() + "/hello.txt");
                OutputStream os = new FileOutputStream(new File(System.getenv("SECONDARY_STORAGE") + "/hello.txt"));

                os.write(b);
                os.close();

                file.close();

                Toast.makeText(this, "write Success.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "File not exists", Toast.LENGTH_LONG).show();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

И я также добавляю разрешение на запись в файл AndroidManifest.xml

AndroidManifest.xml

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

выше программы возвращает правильный путь /storage/extSdCard/hello.txt, но не копирует файл на этот путь, я получил следующую ошибку

W/System.err: java.io.FileNotFoundException: /storage/extSdCard/hello.txt: open failed: EACCES (Permission denied)

, когда ясделать это для внутреннего хранилища, это будет работать, значит, он будет копировать файл во внутреннее хранилище, но не в SDCard.

1 Ответ

0 голосов
/ 22 февраля 2019

В самой последней версии Android вы должны запросить разрешения у пользователя.

Вы можете видеть это: https://developer.android.com/training/permissions/requesting#java

Чтобы запросить разрешение, вы можете сделать это:

// Define a number code for your permission
private final static int MY_PERMISSIONS_REQUEST_WRITE = 42
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.WRITE_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // Permission is not granted
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST_WRITE);

        // MY_PERMISSIONS_REQUEST_WRITE is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

Для обработки результата кода выше, попробуйте это:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request.
    }
}

Если у вас есть какие-либо вопросы, не стесняйтесь.

...