我在为Android程序创建新目录时遇到困难,它没有处理到我的stream方法中。
这是我在MainActivity中的OnClick方法:

public void savnshare(View v){
    if (mBitmap == null){
        return;
    }


    File path = new File(Environment.getExternalStorageDirectory() + "/Bill");
    path.mkdirs(); //Result of 'File.mkdirs()' is ignored
    Random rand = new Random();
    int n = rand.nextInt(20);
    String filename = "bill_"+n+".jpeg";
    File file = new File(path, filename);
    FileOutputStream stream;
    try{
        stream = new FileOutputStream(file);
        mback.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        stream.close();

    }catch (Exception e){
        Toast.makeText(getApplicationContext(),"errr try again...",Toast.LENGTH_SHORT).show();
    }
    Uri uri = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setType("image/*");
    intent.putExtra(Intent.ACTION_SENDTO, uri);
    Intent.createChooser(intent, "Share via...");
    startActivity(intent);

}


我使用的权限:

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


谢谢。

最佳答案

您正在构建M设备。因此,您需要事先获得写入SD卡的许可。

这是它的代码-

private static final int REQUEST_WRITE_STORAGE = 112;


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

    boolean hasPermission = (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }
}

09-08 11:31