2016-11-30 138 views
0

我使用下面的代碼,但它似乎並沒有改變鈴聲。我做錯了什麼,或者有更簡單的方法來設置一個MP3鈴聲?我有一個解析位置的uri,我稱之爲以下函數。我知道uri是正確的,因爲它使用我擁有的文件共享方法正確運行。如何使用鈴聲管理器在Android中設置鈴聲?

private void setRingtone(Uri uri) { 
     AssetFileDescriptor openAssetFileDescriptor; 
     ((AudioManager) getActivity().getSystemService(AUDIO_SERVICE)).setRingerMode(2); 
     File file = new File(Environment.getExternalStorageDirectory() + "/appkeeda", mp3s[position]); 
     if (!file.getParentFile().exists()) { 
      file.getParentFile().mkdirs(); 
     } 
     if (!file.exists()) { 
      try { 
       file.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     ContentResolver contentResolver = getActivity().getContentResolver(); 
     try { 
      openAssetFileDescriptor = contentResolver.openAssetFileDescriptor(uri, "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", "nkDroid ringtone"); 
     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(); 
     } 
    } 
+0

參考http://stackoverflow.com/questions/1271777/how-to-set-ringtone-in-android-from-my-activity – sasikumar

+0

不起作用,但謝謝你,我認爲代碼可能已經過時了 –

回答