我已經設置了一個接收器類收到的鬧鐘,我希望它能播放鈴聲,振動並顯示通知,然後當我點擊通知時應該解除它。在鬧鐘接收器類中使用鈴聲和通知
在通知顯示的那一刻,它會振動,但鈴聲會一直播放,當我點擊通知時,它會再次執行整個代碼,以便另一個鈴聲開始播放,並且通知不會被解除。
這是怎麼回事?
這裏是我的代碼
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("id");
String type = intent.getStringExtra("type");
String time = intent.getStringExtra("time");
String date = intent.getStringExtra("date");
if(type.equals("1")){
msg = "Care UK appointment";
}else{
msg = "Exercise Reminder";
}
for(int i = 0; i < PP.parse2.size(); i++){
if(PP.parse2.get(i).id.equals(id)){
PP.parse2.remove(i);
PP.saveReminder();
break;
}
}
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = msg;
CharSequence message = time+" on "+date;
PendingIntent contentIntent = PendingIntent.getBroadcast(context,
Integer.parseInt(id), intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
am.cancel(contentIntent);
@SuppressWarnings("deprecation")
Notification notif = new Notification(R.drawable.alarm_icon,
msg, System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
//nm.cancel(1);
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(2000);
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mMediaPlayer.stop();
mMediaPlayer.release();
}
});
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
// Get an alarm sound. Try for an alarm. If none set, try notification,
// Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}