我正在使用下面的代码并收到“FileNotFound”异常。谁能解释为什么会这样?我正在使用模拟器进行测试,2.3.3。
private void setRingtone(){
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources().openRawResource(R.raw.custom_ringtone);
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
Log.d("trace", "IO 1" + e);
}
String path = Environment.getExternalStorageDirectory().getPath()+"/media/ringtone/";
String filename = "custom_ringtone.mp3";
boolean exists = (new File(path)).exists();
if (!exists){
new File(path).mkdirs();
Log.d("trace", "path added" + path);
}else{
Log.d("trace", "path not added" + path);
}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
Log.d("trace", "FileNotFound" + e);
} catch (IOException e) {
Log.d("trace", "IO 2" + e);
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Schedule Cheer");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "One2MM");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_RINGTONE, newUri);
}
答案 0 :(得分:1)
请记住,您需要声明写入外部SD卡的权限。
只需将此行添加到<manifest>
代码下的manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />