如果可用,将图像保存到外部存储

时间:2014-06-22 21:37:17

标签: java android

我想将壁纸保存到外部存储器(如果可用),将其保存到设备内部存储器。我的代码适用于安装了外部存储器的设备但在外部存储器不可用时失败。我的短代码发布在

下面
  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 个答案:

答案 0 :(得分: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;
}

你只是检查一个条件!

希望它有所帮助!