2012-08-31 48 views
-1

我使用下面的代碼在2分鐘後得到吐司消息,同時我想添加一個聲音警報。添加聲音警報以及吐司通知?

Calendar cal = Calendar.getInstance(); 
    cal.get(Calendar.DATE); 
    cal.add(Calendar.MINUTE,2); 
    Intent intent = new Intent(this, MyBroadcastReceiver.class); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0); 
      AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 

      alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() 
       , pendingIntent); 

      Toast.makeText(this, "Time to get", 
        Toast.LENGTH_LONG).show(); 

我試着用下面的代碼:

int icon = R.drawable.ic_launcher;  // icon from resources 
      CharSequence tickerText = "Hello";    // ticker-text 
      long when = cal.getTimeInMillis();  // notification time 
      Context context = getApplicationContext();  // application Context 
      CharSequence contentTitle = "My notification"; // message title 
      CharSequence contentText = "Hello World!";  // message text 

      Intent notificationIntent = new Intent(this, MyBroadcastReceiver.class); 
      PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 12345, notificationIntent, 0); 

      // the next two lines initialize the Notification, using the configurations above 
      Notification notification = new Notification(icon, tickerText, when); 
      notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
      notification.defaults |= Notification.DEFAULT_SOUND; 

回答

0

你可以使用SoundPool類,像這樣:

private SoundPool soundPool; 
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 
    soundPoolMap = new HashMap<Integer, Integer>(); 
    //Put your sounds here, from raw resources 
    soundPoolMap.put(SOUND_SCHIVATO, soundPool.load(ctx, R.raw.schivato, 1)); 
    soundPoolMap.put(SOUND_GONG, soundPool.load(ctx, R.raw.gong, 1)); 
    soundPoolMap.put(SOUND_AHH, soundPool.load(ctx, R.raw.ahhh, 1)); 
    ... 

    private void playSound(int sound) { 
     /* Volume calculations */ 
     AudioManager mgr = (AudioManager) ctx 
       .getSystemService(Context.AUDIO_SERVICE); 
     float streamVolumeCurrent = mgr 
       .getStreamVolume(AudioManager.STREAM_MUSIC); 
     float streamVolumeMax = mgr 
       .getStreamMaxVolume(AudioManager.STREAM_MUSIC); 
     float volume = streamVolumeCurrent/streamVolumeMax; 

     /* Play the sound with the correct volume */ 
     soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f); 
} 

在我的項目我做了一個類來管理所有的音頻包含我發佈的代碼段的通知。該課程非常簡單,它只會將我自定義的聲音加載到HashMap中,並公開方法來播放它們。

Context是加載SounPool資源所必需的。一個簡單的教程可用here