为什么我不能使用我的代码保存到外部存储?

Why can't I save to the external storage using my code?

我正在尝试编写一个需要保存到外部存储器的程序。现在我好像无法保存到外部存储。

我添加了必要的权限

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

我的代码是一个简单的写入外部存储的测试。

final Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String path = Environment.getExternalStorageDirectory() + "/Pictures/" + "test.jpg";                
            File file = new File(path);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });

我在模拟器和物理设备上都有 运行 这段代码。在这两种情况下,我都看不到保存到图片文件夹的文件。真的需要帮助。

自 Android M+ 以来,您不仅需要在 Manifest 中请求许可,还需要在运行时请求许可

private void requestPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
        ActivityCompat
                .requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    } else {
        //your permission was already granted then write to storage        
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 1:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
               // here you write to the storage for the first time
            } else {
                // Permission Denied               
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}