2015-01-05 205 views
0

我使用發送通知該代碼將用戶:Android通知播放聲音一次

NotificationManager notificationManager = (NotificationManager) 
      this.getSystemService(Context.NOTIFICATION_SERVICE); 

    Group group = new Group(Integer.parseInt(serverNotification.getGroupID()), serverNotification.getGroupTitle()); 
    Intent intent = new Intent(this, MainActivity.class); 

    if (serverNotification.getType() != Notification.NotificationType.VIDEO_PROCESS_COMPLETED) { 
     intent.putExtra(MainActivity.EXTRA_MODE, MainActivity.MODE_GROUP_VIDEOS); 
     intent.putExtra(MainActivity.EXTRA_GROUP, group); 

     if (serverNotification.getVideoID() != null && serverNotification.getVideoID().length() != 0) { 
      intent.putExtra(MainActivity.EXTRA_VIDEO_ID, serverNotification.getVideoID()); 
     } 
    } 

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

    android.app.Notification.Builder builder = new android.app.Notification.Builder(this) 
      .setSmallIcon(R.drawable.notification_icon) 
      .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) 
      .setWhen(System.currentTimeMillis()) 
      .setContentText(serverNotification.getMessage()) 
      .setTicker(serverNotification.getMessage()) 
      .setAutoCancel(true) 
      .setContentTitle("MyApp"); 

    builder.setContentIntent(contentIntent); 

    if (Build.VERSION.SDK_INT >= 16) { 
     notificationManager.notify(GROUP_NOTIFICATION_ID++, builder.build()); 
    } else { 
     notificationManager.notify(GROUP_NOTIFICATION_ID++, builder.getNotification()); 
    } 

    try { 
     Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); 
     r.play(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

的問題是,當我得到(連續3+)多個通知它播放聲音多次,有是隻有一次播放聲音的方法嗎?

回答

0

你並不需要自己播放的聲音 - 嘗試:

builder.setSound( RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

甚至更​​好,因爲你使用的是默認的聲音: builder.setDefaults(Notification.DEFAULT_SOUND);

而剛剛通過的方式 - 避免在代碼中使用顯式數字(和文字),請使用常量: Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN而不是Build.VERSION.SDK_INT < 16。它確實提高了代碼的可讀性。