如何在android中的不同时间设置多个警报

时间:2014-05-30 11:49:37

标签: android android-alarms

我正在做一个Android应用程序,我需要在不同的时间设置多个警报。例如。我需要设置每天@ 10 AM,PM9PM。我想用这些时间设置重复闹钟&当这个时代到来时,它们会被束缚起来。这三个戒指应该每天都发生。下面是我试过的样本代码。但它没有环绕。我怎么能解决这个问题?谢谢。

我的代码: ...

            // For setting up hours as arrays

    h[0] = 10;
    h[1] = 14;
    h[2] = 21;

    Calendar cal[] = new Calendar[3];

    for (int i = 0; i < 3; i++) {
        cal[i] = Calendar.getInstance();
        cal[i].set(Calendar.HOUR_OF_DAY, h[i]);
        cal[i].set(Calendar.MINUTE, i);
        cal[i].set(Calendar.SECOND, i);
    }

    AlarmManager[] alarmManager = new AlarmManager[3];
    ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
    for (int f = 0; f < cal.length; f++) {
        Intent intent = new Intent(AlarmMainActivity.this,
                AlarmReceiverActivity.class);
        PendingIntent pi = PendingIntent.getBroadcast(
                AlarmMainActivity.this, f, intent, 0);

        alarmManager[f] = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager[f].set(AlarmManager.RTC_WAKEUP,
                cal[f].getTimeInMillis(), pi);

        intentArray.add(pi);

    }

}

我的AlarmReceiverActivity:

...

    Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
    stopAlarm.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View arg0, MotionEvent arg1) {
            mMediaPlayer.stop();
            finish();
            return false;
        }
    });

    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();
        }
    } 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;
}

0 个答案:

没有答案