单个闹铃是实现了,但多个闹铃实现不了!比如我第一个闹铃的时间设置为Thur May 14 23:33:00 CST (China) 2015,第二个闹铃的时间设置为Thur May 14 23:25:00 CST (China) 2015,然后到了23:25分的时候,两个闹铃就一起响了!!!下面我把主要代码贴上来!
package com.android.alarms;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
public class MainActivity extends Activity {
private Button btn = null;
private AlarmManager alarmManager = null;
Calendar cal = Calendar.getInstance();
final int DIALOG_TIME = 0; // 设置对话框id
int i = 0;
ArrayList<String> time = new ArrayList<String>();; // 保存在数据库读取到的时间
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
btn = (Button) findViewById(R.id.setAlarm);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//假设把在数据库读取到的数据增加到数组
time.add("Thur May 14 23:47:00 CST (China) 2015");
showDialog(DIALOG_TIME);// 显示时间选择对话框
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_TIME:
dialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
time.add(c.getTime().toString());//把在程序界面设置的时间添加到数组
// 如果数组是空的,直接创建闹铃,否则用数组的值创建多个闹铃
if (time.isEmpty()) {
Intent intent = new Intent(MainActivity.this,
AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(
MainActivity.this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), pi); // 设置闹钟
} else {
while(i < time.size()) {
Intent intent = new Intent(MainActivity.this,
AlarmReceiver.class);
PendingIntent pi = PendingIntent
.getBroadcast(MainActivity.this, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String dateTime = time.get(i);
Log.v("第" + i + "个时间", dateTime);
try {
c.setTime(new SimpleDateFormat(
"yyyyMMddHHmmss")
.parse(dateTime)); // 将字符串转化为毫秒
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
alarmManager.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), pi); // 用把转换为毫秒后的数组的值设置闹钟
i++;
}
}
}
}, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
false);
break;
}
return dialog;
}
}
------解决思路----------------------
能否debug看下,为什么两个闹铃会响,估计是逻辑有问题