2012-08-05 106 views
0

新的文件我有一個問題,我想設置我的主要acivity內的鈴聲,我閱讀本教程:http://androidgenuine.com/?tag=set-as-ringtone-android,但保存功能不能正常工作,更具體的我不能創建一個文件,函數返回false。我又只寫與創建新的文件,但即使這部分不能正常工作,這裏是代碼,有什麼不對的一部分(它; S返回false和非文件的創建)?使android系統

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; 
    } 
} 

感謝您的幫助

+0

您可以加入一些logcat的輸出? – cyroxx 2012-08-05 20:29:45

回答

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; 
    }