如下是为Notification自定义铃声的部分片段
- 铃声选择(已记住上次选择的铃声)
_btnNotificationChooseRington .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent( RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); Uri ringtongUri = null; final SharedPreferences sharedPreferences = MoreSettingActivity.this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); String uri = sharedPreferences.getString(CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG, "null"); if("null".equals(uri)) { ringtongUri = (Uri) null; } else { ringtongUri = android.net.Uri.parse(uri); } intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TITLE, getString(R.string.notification_ringtong)); intent.putExtra( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,ringtongUri); startActivityForResult( intent, RESULT_FIRST_USER); } });
- 铃声保存(注意静音保存为null)
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, String.format("requestCode=%d,resultCode = %d", requestCode, resultCode)); if (resultCode == RESULT_OK ) { Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if (uri != null) { String ringTonePath = uri.toString(); SharedPreferences _prefse = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); _prefse.edit().putString(CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG, ringTonePath).commit(); } else {Log.d(TAG, "null"); SharedPreferences _prefse = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); _prefse.edit().putString(CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG, "null").commit(); } } else if (resultCode == RESULT_CANCELED) { } super.onActivityResult(requestCode, resultCode, data); }
- 铃声设置
private boolean isNotificationSoundEnabled() { //return sharedPrefs.getBoolean(Constants.SETTINGS_SOUND_ENABLED, true); return !sharedPrefs.getString(CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG, "null").equals("null"); } private boolean isNotificationVibrateEnabled() { return sharedPrefs.getBoolean(Constants.SETTINGS_VIBRATE_ENABLED, true); } if(isNotificationSoundEnabled()&&isNotificationVibrateEnabled()){ notification.sound = android.net.Uri.parse(sharedPrefs.getString(CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG, Settings.System.DEFAULT_NOTIFICATION_URI.toString())); long[] vibrate = {0,100,200,300}; notification.vibrate = vibrate; } else if (isNotificationSoundEnabled()&&!isNotificationVibrateEnabled()) { notification.sound = android.net.Uri.parse(sharedPrefs.getString(CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG, Settings.System.DEFAULT_NOTIFICATION_URI.toString())); //notification.defaults = Notification.DEFAULT_SOUND; }