2014-03-26 156 views
0

我在尝试为通知警报声设置持续时间时遇到了一些问题。下面是它现在的样子:Android:通知声音持续时间

NotificationManager mNotificationManager = (NotificationManager) context 
      .getSystemService(Context.NOTIFICATION_SERVICE); 
    // mId allows you to update the notification later on. 
    mBuilder.setAutoCancel(true); 

    Uri alarmSound = Uri.parse(sharedPref.getString(
       "notifications_new_message_ringtone", "")); 

    if (alarmSound != null) { 
     mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); 
     try { 
      mediaPlayer.setDataSource(context, alarmSound); 
      mediaPlayer.prepare(); 
     } catch (IllegalArgumentException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SecurityException e) { 

     } 

     mBuilder.setSound(alarmSound); 



     mNotificationManager.notify(notificationId, mBuilder.build()); 

     new Thread() { 
      public void run() { 

       try { 
        sleep(sharedPref.getInt("alarm_duration",2000) * DateUtils.SECOND_IN_MILLIS); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       mNotificationManager.cancel(notificationId); 
      } 
     }.start(); 
    } 

正如你所看到的,我通过sharedPref变量赋予了一段时间后停止的通知(用户可以设置此)。事情是,这条线:“mNotificationManager.cancel(notificationId)”不仅会停止声音,而且会阻止整个通知(灯光,振动,甚至是通知抽屉中的图标)。

是否有办法在不完全取消通知的情况下关闭通知?

在此先感谢!

回答

1

没有办法只取消声音。您可以取消整个Notification,然后在没有声音的情况下再次发布。或者,您可以将AudioManager.STREAM_NOTIFICATION流类型静音为x时间量,然后在Notification声音结束后取消静音。

要控制音量:

setVolumeControlStream(AudioManager.STREAM_NOTIFICATION); 

要静音Notification声音:

final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
    am.setStreamMute(AudioManager.STREAM_NOTIFICATION, true or false); 
+0

谢谢! :)我喜欢第一种方法。我会让你知道它是怎么回事。 – feresr

+0

我无法实现此:setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);因为我不在一项活动中(我在广播接收器上)。至于第二块代码,它似乎没有太多:( – feresr

+0

@ user1949554 [Activity.setVolumeControlStream](http://bit.ly/1ggCVOk) – adneal

0

你知道当一个通知来在发生什么,你触摸通知栏?它不取消通知,只是停止它的声音。似乎应该有一种方法来执行相同的代码。