How to set ringtone in Android from my activity?

后端 未结 9 1561
一个人的身影
一个人的身影 2020-11-22 12:11

I\'m trying to find a way to set a new default ringtone by code from my Android activity.

I have already downloaded the ringtone into a bytearray.

9条回答
  •  悲&欢浪女
    2020-11-22 12:44

    public void setRingtone() {
      String ringtoneuri = Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/ringtone";
      File file1 = new File(ringtoneuri);
      file1.mkdirs();
      File newSoundFile = new File(ringtoneuri, "myringtone.mp3");
    
    
      Uri mUri = Uri.parse("android.resource://globalapps.funnyringtones/raw/sound_two.mp3");
    
    
      ContentResolver mCr = this.getContentResolver();
      AssetFileDescriptor soundFile;
      try {
       soundFile = mCr.openAssetFileDescriptor(mUri, "r");
      } catch (FileNotFoundException e) {
       soundFile = null;
      }
    
      try {
       byte[] readData = new byte[1024];
       FileInputStream fis = soundFile.createInputStream();
       FileOutputStream fos = new FileOutputStream(newSoundFile);
       int i = fis.read(readData);
    
       while (i != -1) {
        fos.write(readData, 0, i);
        i = fis.read(readData);
       }
    
       fos.close();
      } catch (IOException io) {
      }
    
      ContentValues values = new ContentValues();
      values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());
      values.put(MediaStore.MediaColumns.TITLE, "my ringtone");
      values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
      values.put(MediaStore.MediaColumns.SIZE, newSoundFile.length());
      values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
      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);
    
      Uri uri = MediaStore.Audio.Media.getContentUriForPath(newSoundFile.getAbsolutePath());
      Uri newUri = mCr.insert(uri, values);
      try {
       Uri rUri = RingtoneManager.getValidRingtoneUri(this);
       if (rUri != null)
        ringtoneManager.setStopPreviousRingtone(true);
       RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
       Toast.makeText(this, "New Rigntone set", Toast.LENGTH_SHORT).show();
      } catch (Throwable t) {
       Log.e("sanjay in catch", "catch exception"+e.getMessage());
      }
    
     }
    

提交回复
热议问题