List the files in Download directory of the Android phone

前端 未结 2 1889
一生所求
一生所求 2021-02-09 18:48

I am using the following code for trying to list the files in Download directory.

I build the apk, install it on my phone and then run it. I have files in both Internal

2条回答
  •  悲哀的现实
    2021-02-09 19:30

    Add storage permission to your project manifest file:

    
    

    and ask the user to grant the permission like this:

    int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
    

    add this method to your code:

    public static boolean hasPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
    

    and it is optional to override this:

        @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) {
    
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Toast.makeText(getApplicationContext(), "permission was granted", Toast.LENGTH_SHORT).show();
    
                } else {
    
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }
    

    now you can use the below code to access your application Download directory:

    context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    

    Good Luck :)

提交回复
热议问题