0

我有一个问题,我想在我的主要活动中设置一个铃声,我阅读了这个教程:http ://androidgenuine.com/?tag=set-as-ringtone-android ,但是功能保存不起作用,更多具体我无法创建文件,函数返回false。我只写了一个创建新文件的部分,但即使这部分也不起作用,这是代码,有什么问题(它返回错误并且未创建文件)?

    public boolean save2(int ressound){

    String path="/sdcard/sounds/";
    String filename="ring.mp3";
    byte[] buffer = null;
    FileOutputStream save;
    InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
    int size=0;
    try {
        size=fIn.available();
        buffer = new byte[size];
        fIn.read(buffer);
        fIn.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        save = new FileOutputStream(path+filename);
        save.write(buffer);
        save.flush();
        save.close();
        return true;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}

谢谢你的帮助

4

1 回答 1

2

我只能猜测您指定的目录可能不存在,或者您没有在清单中设置适当的权限。

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

您应该使用以下文档中的以下内容构建它

http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory ()

File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

// Make sure the Pictures directory exists.
path.mkdirs();

您还必须检查外部存储是否已安装。

String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }
于 2012-08-05T20:38:47.463 回答