1

我很難爲我的Android程序創建新的目錄,它不會處理到我的stream方法中。 這裏是我的OnClick方法在MainActivity:在外部存儲API上創建新目錄23

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"/> 

謝謝。

回答

4

您正在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(); 
      } 
     } 
    } 
} 
+1

感謝它幫助很多 –

相關問題