我使用下面的代码在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 :(得分: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
。有一个简单的教程here