0

我正在尝试让我的 Android 应用程序将 mp3 从应用程序保存到 sd 卡,以便以后使用,但它不会将文件保存在手机中的任何位置。在我的 AndroidManifest 文件中,我有权写入外部存储。这是我到目前为止的代码:

public void onClick(View v) {
        int ressound = R.raw.hodor1;
        saveas(ressound);
    }

public boolean saveas(int ressound){
     byte[] buffer=null;
     InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
     int size=0;

     //1st part
     try {
      size = fIn.available();
      buffer = new byte[size];
      fIn.read(buffer);
      fIn.close();
     } catch (IOException e) {
         Log.e(TAG, "IOException first part");
      return false;
     }

     String soundname = "hodor1";
     String filename = soundname +".mp3";
     String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
     File fullPath = new File(path, filename);

     boolean exists = (new File(path)).exists();
     if (!exists){new File(path).mkdirs();}

     //second part
     FileOutputStream save;
     try {
         save = new FileOutputStream(fullPath);
         save.write(buffer);
         save.flush();
         save.close();
     } catch (FileNotFoundException e) {
         Log.e(TAG, "FileNotFoundException in second part");
         return false;
     } catch (IOException e) {
         Log.e(TAG, "IOException in second part");
         return false;
     }    

     //not working
     //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, soundname);
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
     values.put(MediaStore.Audio.Media.ARTIST, "Elvis");
     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 newUri = this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

     // set as ringtone
     //savetype = RingtoneManager.TYPE_RINGTONE;
     //RingtoneManager.setActualDefaultRingtoneUri(this, savetype, newUri);

     return true;
    }
4

1 回答 1

0

Commonsware 最准确地回答了我的帖子。Environment.getExternalStoragePublicDirectory() 应与适当的编程技术(如日志记录)和使用两个参数的文件构造函数一起使用。

于 2013-06-16T02:10:17.797 回答