某些设备无法播放通知声音

时间:2016-04-13 17:40:49

标签: android

我的Android应用程序使用声音通知。 它适用于某些Android /设备,但与其他设备不太一样。

使用摩托罗拉MZ604,android 4.0.4,它运行正常。 使用LG G3 Android 5.0,会显示通知并且手机会振动,但没有声音。 我还测试了一个针对API 22的Android模拟器,它运行良好。

我正在使用广播接收器来创建意图并播放声音,代码如下:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
    .setAutoCancel(true)
    .setSmallIcon(R.drawable.ic_launcher)
    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
    .setContentText(message.getText())
    .setContentTitle(message.getTitle())
    .setPriority(Notification.PRIORITY_MAX);

Intent notificationIntent;
notificationIntent = new Intent(context, ListTrackersActivity_.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("notificationTitle", message.getTitle());
notificationIntent.putExtra("notificationMessage", message.getText());
notificationIntent.putExtra(ListTrackersActivity.PARAMETERS, message.getParameters());

final AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
                                   @Override
                                   public void onAudioFocusChange(int focusChange) {
                                       if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                                           audioManager.abandonAudioFocus(this);
                                       }
                                   }
                               }, AudioManager.STREAM_ALARM,
        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if(alarmSound == null){
    alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    if(alarmSound == null){
        alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    }
}
mBuilder.setSound(alarmSound, AudioManager.STREAM_ALARM);

int uniqueInt = (int) (System.currentTimeMillis() & 0xfffffff);
PendingIntent contentIntent = PendingIntent.getActivity(context, uniqueInt, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);

NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, mBuilder.build());

0 个答案:

没有答案