2014-06-22 70 views
0

如果可用,我希望将壁纸保存到外部存储器,否则请将其保存到设备的内部存储器中。我的代码适用于装有外部存储器的设备,但在外部存储器不可用时会失败。我的短代码下面贴将图像保存到外部存储器(如果可用)

public FileOutputStream getOutStream(String fileName) throws FileNotFoundException{ 
    if (Environment.getExternalStorageState().equals(
      Environment.MEDIA_MOUNTED)) { 
     String sdpath = Environment.getExternalStoragePublicDirectory(
       Environment.DIRECTORY_PICTURES) 
       + "/"; 
     mSavePath = sdpath + "DroidPack"; 
     File file = new File(mSavePath); 
     if (!file.exists()) { 
      file.mkdir(); 
     } 
     File saveFile = new File(mSavePath, fileName); 

     return new FileOutputStream(saveFile); 


    }else{ 
     String sdpath = mContext.getFilesDir().getPath() + "/"; 
     mSavePath = sdpath + "DroidPack"; 
     File file = new File(mSavePath); 
     if (!file.exists()) { 
      file.mkdir(); 
     } 
     return mContext.openFileOutput(fileName , Context.MODE_WORLD_READABLE); 
     } 
} 

}

回答

1

看看在Android Documentation

不过,你应该试试这个:

boolean mExternalStorageAvailable = false; 
boolean mExternalStorageWriteable = false; 
String state = Environment.getExternalStorageState(); 

if (Environment.MEDIA_MOUNTED.equals(state)) { 
    // We can read and write the media 
    mExternalStorageAvailable = mExternalStorageWriteable = true; 
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
    // We can only read the media 
    mExternalStorageAvailable = true; 
    mExternalStorageWriteable = false; 
} else { 
    // Something else is wrong. It may be one of many other states, but all we need 
    // to know is we can neither read nor write 
    mExternalStorageAvailable = mExternalStorageWriteable = false; 
} 

你只是检查一个条件!

希望它有帮助!

相关问题