在代码中设置默认铃声的问题

时间:2012-02-19 22:14:48

标签: android eclipse ringtone

  

可能重复:
  How to clear Mediastore before setting ringtone

我的Android应用程序中有一组约130个mp3的不同声音片段。它们列在列表视图中,当用户长按其中一个时,它可以选择将其设置为默认铃声或通知。在大多数情况下,我让这个用于铃声,但它有点不一致。

例如,它可能会首次设置默认铃声,但下次我尝试将另一个片段设置为默认铃声,然后进入我的铃声列表时,会选择“静音”。另外,我注意到在整个测试过程中,应用程序在我的铃声列表中创建了3-4个没有相应文件的选项,我不知道如何删除它们。

我不是一个非常有经验的Android开发者,所以,我无法弄清楚我在这里做错了什么。这是我的setRingtone()的代码,其中传递了res​​ourceid:

public void playSound(int input){
    byte[] buffer=null;
    InputStream fIn = getBaseContext().getResources().openRawResource(input);
    int size=0;

    try {
        size = fIn.available();
        buffer = new byte[size];
        fIn.read(buffer);
        fIn.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    String path="/sdcard/sounds/";
    String filename="my_ringtone"+".mp3";

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

    FileOutputStream save;
    try {
        save = new FileOutputStream(path+filename);
        save.write(buffer);
        save.flush();
        save.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    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, "MyRingtone");
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
    values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    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);
    RingtoneManager.setActualDefaultRingtoneUri(
    this,
    RingtoneManager.TYPE_RINGTONE,
    newUri
    );
}

1 个答案:

答案 0 :(得分:0)

最有可能的是,getBaseContext是您的问题。基本上下文将随着其他事情的发生而改变。您需要应用的上下文。

相关问题