从 SharedPreferences 将铃声加载到 Mediaplayer

Load Ringtone into Mediaplayer from SharedPreferences

恐怕我对 URI 在这里的工作方式存在某种根本性的误解。我正在尝试将此警报音保存到我的 SharedPreferences 文件中,然后以相同的方式恢复它。

我认为问题在于我如何解析 URI,我不是特别了解如何检索 URI

我已尝试将以下内容存储到我的共享首选项中。

//the displayed name of the ringtone
RingtoneManager.getRingtone(this, uri).getTitle(this)

data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)

每个字符串都正确恢复,但我不知道我需要解析的实际密钥以检索我正在寻找的警报音。

获取偏好如下

/** Restore alarm tone and update UI */
        if (mSettings.contains(ALARM_TONE)){
            alarmTone = mSettings.getString(ALARM_TONE, null);
            if (alarmTone != null) {

                uri = Uri.parse(alarmTone);
                TextView t = (TextView) findViewById(R.id.alarmTone);
                t.setText(RingtoneManager.getRingtone(this, uri).getTitle(this));

                mp = MediaPlayer.create(getApplicationContext(), uri);
            }
        }

我找到的解决方案使用 Uri.toString() 将 Uri 保存到首选项。使用 Uri.parse(preferenceString)

加载铃声

onActivityresult,我立即将uri字符串保存到我的偏好

    /** For selecting an alarmtone */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ALARM_URI:
                    uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                    TextView mTextView = (TextView) findViewById(R.id.alarmTone);
                    mTextView.setText(RingtoneManager.getRingtone(this, uri).getTitle(this));

                    mp = new MediaPlayer();
                    mp = MediaPlayer.create(getApplicationContext(), uri);

                    mp.setLooping(true);

                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(ALARM_TONE, uri.toString());
                    editor.commit();

                    break;

                default:
                    break;
            }
        }
    }

从这里开始加载 URI

       if (mSettings.contains(ALARM_TONE)){
            alarmTone = mSettings.getString(ALARM_TONE, null);
            if (alarmTone != null) {
                uri = Uri.parse(alarmTone);
                //update textview to loaded alarm tone
                TextView t = (TextView) findViewById(R.id.alarmTone);
                t.setText(RingtoneManager.getRingtone(this, uri).getTitle(this));

                mp = MediaPlayer.create(getApplicationContext(), uri);
            }
        }