如何以编程方式从铃声设置默认铃声

问题描述:

我想从原始文件夹中设置一个MP3作为手机的铃声。铃声存储在铃声文件夹中,是一个可供选择的选项,但我希望将铃声选作默认铃声。我怎样才能以编程方式做到这一点?如何以编程方式从铃声设置默认铃声

private void setRingtone() { 
     AssetFileDescriptor openAssetFileDescriptor; 
     ((AudioManager) getActivity().getSystemService(AUDIO_SERVICE)).setRingerMode(2); 
     File file = new File(Environment.getExternalStorageDirectory() + "/appkeeda", this.fNmae); 
     if (!file.getParentFile().exists()) { 
      file.getParentFile().mkdirs(); 
     } 
     if (!file.exists()) { 
      try { 
       file.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     Uri parse = Uri.parse(this.fPAth); 
     ContentResolver contentResolver = getActivity().getContentResolver(); 
     try { 
      openAssetFileDescriptor = contentResolver.openAssetFileDescriptor(parse, "r"); 
     } catch (FileNotFoundException e2) { 
      openAssetFileDescriptor = null; 
     } 
     try { 
      byte[] bArr = new byte[1024]; 
      FileInputStream createInputStream = openAssetFileDescriptor.createInputStream(); 
      FileOutputStream fileOutputStream = new FileOutputStream(file); 
      for (int read = createInputStream.read(bArr); read != -1; read = createInputStream.read(bArr)) { 
       fileOutputStream.write(bArr, 0, read); 
      } 
      fileOutputStream.close(); 
     } catch (IOException e3) { 
      e3.printStackTrace(); 
     } 
     ContentValues contentValues = new ContentValues(); 
     contentValues.put("_data", file.getAbsolutePath()); 
     contentValues.put("title", mp3s[position]); 
     contentValues.put("mime_type", "audio/mp3"); 
     contentValues.put("_size", Long.valueOf(file.length())); 
     contentValues.put("artist", Integer.valueOf(R.string.app_name)); 
     contentValues.put("is_ringtone", Boolean.valueOf(true)); 
     contentValues.put("is_notification", Boolean.valueOf(false)); 
     contentValues.put("is_alarm", Boolean.valueOf(false)); 
     contentValues.put("is_music", Boolean.valueOf(false)); 
     try { 
      //Toast.makeText(this, new StringBuilder().append("Ringtone set successfully"), Toast.LENGTH_LONG).show(); 
      RingtoneManager.setActualDefaultRingtoneUri(getActivity().getBaseContext(), 1, contentResolver.insert(MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath()), contentValues)); 
     } catch (Throwable th) { 
      //Toast.makeText(this, new StringBuilder().append("Ringtone feature is not working"), Toast.LENGTH_LONG).show(); 
     } 
    } 

如果你有一个PreferenceScreen了它的铃声选择部分,你可以创建它RingtonePreference项目,这将让用户决定的铃声。更多关于首herehere,也为RingtonePreference

以后,您可以使用sharedPreferences获取此铃声,甚至为它设置一个默认值。看看这个post

+1

非常感谢bro(或sis):) –