无法请求SD卡访问应用程序和删除SD卡上的文件

时间:2018-02-19 10:33:10

标签: java android android-5.0-lollipop android-permissions android-sdcard

我在SO上阅读了很多关于如何请求访问SD卡和删除文件的问题,但我仍然无法使用我的应用程序。 我试图在用户尝试删除SD卡上的文件时请求访问权限,然后在获得权限后删除该文件。
这是我尝试过的:

public static boolean permissiongranted = true;
    public static boolean deletebuttonclicked =false;

button3.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View view) {
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(SDCard.this);
                        builder1.setMessage("Are you sure you want to delete it ?");
                        builder1.setCancelable(true);

                        builder1.setPositiveButton(
                                "Yes",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        if(permissiongranted){
                                            Log.v(TAG,"here");
                                            deletebuttonclicked=true;
                                            access();
                                        }

                                    }
                                });

                        builder1.setNegativeButton(
                                "No",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                        AlertDialog alert11 = builder1.create();
                        alert11.show();
                    }
                });

private void access(){
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        startActivityForResult(intent, 42);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        if (resultCode == RESULT_OK) {
            Uri treeUri = resultData.getData();
            DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);

            // List all existing files inside picked directory
            for (DocumentFile file : pickedDir.listFiles()) {
                Log.d(TAG, "Found file " + file.getName() + " with size " + file.length());
            }

            // Create a new file and write into it
            DocumentFile newFile = pickedDir.createFile("text/plain", "My Novel");
            if(deletebuttonclicked){
                adapter.deleteItem();
                Log.v(TAG,"executed");
            }
            try {
                OutputStream out = getContentResolver().openOutputStream(newFile.getUri());
                out.write("A long time ago...".getBytes());
                out.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            permissiongranted = false;
        }
    }

主要活动中的运行时权限:

 private void buttonClicked(View view) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
                .checkSelfPermission(this,
                        Manifest.permission.INTERNET) + ContextCompat
                .checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) && ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE))  {

                Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();

            } else {

                Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }
@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
                            .show();


                } else {

                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied", Toast.LENGTH_SHORT)
                            .show();

                }
                return;
            }

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

清单文件中的权限:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
        <uses-permission android:name="android.permission.INTERNET" />

删除适配器类中文件的方法:

protected void deleteItem() {
        for (int i = 0; i < mSelected.size(); i++) {
            Log.v(TAG, mSelected.get(i));
            Log.v(TAG, mData2.get(Integer.parseInt(mSelected.get(i))));
            File file = new File(mData2.get(Integer.parseInt(mSelected.get(i))));
            if(file.isDirectory()){
                String[] children = file.list();
                for (int j = 0; j < children.length; j++)
                {
                    new File(file, children[i]).delete();
                    mData2.remove(Integer.parseInt(mSelected.get(i)));
                }
            }
            Log.v(TAG, file.toString());
            file.delete();
            mData2.remove(Integer.parseInt(mSelected.get(i)));
            MediaScannerConnection.scanFile(context,new String[] { file.toString() }, null, new MediaScannerConnection.OnScanCompletedListener()
            {
                public void onScanCompleted(String path, Uri uri)
                {
                    Log.i("ZAA", "Scanned " + path + ":");
                    Log.i("ZAA", "-> uri=" + uri);
                }
            });
        }
        notifyDataSetChanged();

    }

LOGCAT:

02-19 16:09:18.700 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: 0
02-19 16:09:18.719 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: /storage/F2A7-15EE
02-19 16:09:26.042 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: 0  final size
02-19 16:09:26.042 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: 0 is the size
02-19 16:09:26.043 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: 1 this is size
02-19 16:09:29.751 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: here
02-19 16:09:41.380 23271-23271/com.example.dell_1.Myapp3 D/com.example.dell_1.myapp3.InternalMemory: Found file LOST.DIR with size 32768
02-19 16:09:41.404 23271-23271/com.example.dell_1.Myapp3 D/com.example.dell_1.myapp3.InternalMemory: Found file .android_secure with size 32768
02-19 16:09:42.470 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: 37
02-19 16:09:42.470 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: /storage/F2A7-15EE/My Novel (1).txt
02-19 16:09:42.471 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: /storage/F2A7-15EE/My Novel (1).txt
02-19 16:09:42.506 23271-23271/com.example.dell_1.Myapp3 V/com.example.dell_1.myapp3.InternalMemory: executed

0 个答案:

没有答案