Android File.listFiles()返回null问题

File.listFiles()返回null可能原因是没读取sdcard权限(READ_EXTERNAL_STORAGE WRITE_EXTERNAL_STORAGE)。

system/private-app默认都有权限,system/app某些系统模式下初始化后没权限,系统重启后有权限,第三方app的权限大部分是询问。

使用ContextCompat.checkSelfPermission检查是否有权限,使用ActivityCompat.requestPermissions申请权限。

public class MainActivity extends AppCompatActivity {

    private final static String PATH = Environment.getExternalStorageDirectory().getPath();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (isStoragePermissionGranted()) {
            File directory = new File(PATH);
            File[] files = directory.listFiles();
            Log.i("juno", PATH + "files : " + (files == null ? null : files.length));
        }
    }

    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            final Context context = getApplicationContext();
            int readPermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (readPermissionCheck == PackageManager.PERMISSION_GRANTED 
                    && writePermissionCheck == PackageManager.PERMISSION_GRANTED) {
                Log.v("juno", "Permission is granted");
                return true;
            } else {
                Log.v("juno", "Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else { //permission is automatically granted on sdk<23 upon installation
            Log.v("juno", "Permission is granted");
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.v("juno","onRequestPermissionsResult requestCode : " + requestCode
                + " Permission: " + permissions[0] + " was " + grantResults[0]
                + " Permission: " + permissions[1] + " was " + grantResults[1]
        );
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            //resume tasks needing this permission
            File directory = new File(PATH);
            File[] files = directory.listFiles();
            Log.i("juno", "After PERMISSION_GRANTED files : " + (files == null ? null : files.length));
        }
    }
}

 

你可能感兴趣的:(Android)