Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

android - setting audio file as Ringtone

I have save file in sdcard/media/audio/ringtones folder. That file will appear in list of ringtone selection from settings/sound/phone Ringtone.

But I want to set that file as a ringtone from my code. Here is my code.

  File k = new File(path, filename);

  ContentValues values = new ContentValues();
  values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
  values.put(MediaStore.MediaColumns.TITLE, "TwiAppclip");
  values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
  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);

  Uri uri = MediaStore.Audio.Media.getContentUriForPath(k
       .getAbsolutePath());
  Uri newUri = getApplicationContext().getContentResolver().insert(uri, values);

  RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(),
      RingtoneManager.TYPE_RINGTONE, newUri);

here uri I am getting But I got newUri = null. I think that's why its is not setting as ringtone.

Anyone know where is the problem? how do I get newUri proper?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Audio is set as ringtone only once, but solution to this problem is - If you are trying to run the same code again, you'll be inserting a duplicate entry into MediaStore's table, but the SQLite database won't allow you. You have to either rename your file and add another instance of it, or go in, remove the entry, and then try again. So I removed that entry every time and then insert it again.

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(activity.this,
        RingtoneManager.TYPE_RINGTONE, newUri);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...