我知道这个问题已经存在,我向你保证我已经阅读了答案,没有人帮助过我,因为我的案例是针对RingtonePreference的结果
以下是我用于推送通知接收器服务的代码... 我从RingtonePreference获取铃声首选项,当您在Android Studio中创建设置活动时,默认情况下会创建该铃声首选项。
铃声的偏好会吐出这样的URI:
content://media/internal/audio/media/38
问题在于,无论用户在首选项中选择了什么声音,即使我直接从此选择中解析URI,每次都会播放手机的默认声音!
非常感谢任何帮助。
仅供参考:我还尝试将声音设置为null
,然后使用此代码段手动播放铃声:
Ringtone ringtone = RingtoneManager.getRingtone(preference.getContext(), Uri.parse(stringValue));
ringtone.play();
但是发生的事情是疯狂的。默认铃声STILL播放,并且所选铃声同时播放。 HELP !!!
感谢!!!
public class GCMPushReceiverService extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Boolean doNotify = sp.getBoolean("notifications", true);
Log.e("Notification", "Receiving a notification!");
if(doNotify) {
notifyUser(message, sp);
}
else{
Log.e("Notification", "User has requested not to receive notifications");
}
}
private void notifyUser(String message, SharedPreferences sp) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;//Your request code
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = null;
String preferedRingtone = sp.getString("notifications_ringtone", "");
Log.e("Notification", "Preparing to notify user!");
if(preferedRingtone.equals("")) {
Log.e("Notification", "User has no pref yet, use default");
sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
else{
sound = Uri.parse(preferedRingtone);
Log.e("Notification", "Requested ringtone: " + sound.toString());
}
//Build notification
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My App")
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.PRIORITY_HIGH)
.setSound(sound);
Boolean vibratePref = sp.getBoolean("notifications_vibrate", true);
if(vibratePref){
Log.e("Notification", "User has requested vibrate!");
noBuilder.setVibrate(new long[]{0, 1000, 0, 1000});
}
else {
Log.e("Notification", "User has requested no vibrate!");
noBuilder.setVibrate(null);
}
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
}
}