我正在制作一款Android应用。目的是在预定时间响铃并开启活动。我使用了stackoverflow和其他网站上的几个关于这样做的链接,但是我遇到了一个问题:当我更改TimePicker的时间时,不是设置闹钟,而是设置闹钟并且活动打开。
我希望在更改时间时不打开活动,但只启用闹钟。
这是我的代码:
使用TimePicker的活动:
tp_clock.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
int alarmHours = tp_clock.getCurrentHour();
int alarmMinutes = tp_clock.getCurrentMinute();
Long time = calculateTime(alarmHours, alarmMinutes);
Toast.makeText(context, "Alarm set", Toast.LENGTH_LONG).show();
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
});
calculateTime函数:
public Long calculateTime(int alarmHours, int alarmMinutes)
{
Calendar c = Calendar.getInstance();
int currentHours = c.get(Calendar.HOUR);
if (c.get(Calendar.AM_PM) == 1)
currentHours +=12;
int currentMinutes = c.get(Calendar.MINUTE);
int setAlarmHours = 0;
int setAlarmMinutes = 0;
int balanceWithMinute = 0;
if (alarmMinutes >= currentMinutes)
{
setAlarmMinutes = alarmMinutes - currentMinutes;
}
else
{
setAlarmMinutes = (60 - currentMinutes) + alarmMinutes;
balanceWithMinute = 1;
}
if (alarmHours > currentHours)
setAlarmHours = alarmHours - currentHours;
if (alarmHours < currentHours)
setAlarmHours = (24 - currentHours) +alarmHours - balanceWithMinute;
if (alarmHours == currentHours && balanceWithMinute == 1)
setAlarmHours = 23;
Long time = new GregorianCalendar().getTimeInMillis()+setAlarmHours*setAlarmMinutes*60*1000;
return time;
}
alarmReciever代码:
public class AlarmReciever extends BroadcastReceiver
{
private String userToken;
private String userId;
@Override
public void onReceive(Context context, Intent intent)
{
Intent i=new Intent(context, PlanASoundActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
userToken = intent.getStringExtra(LoginActivity.USER_TOKEN);
userId = intent.getStringExtra(LoginActivity.USER_ID);
i.putExtra(LoginActivity.USER_TOKEN, userToken);
i.putExtra(LoginActivity.USER_ID, userId);
context.startActivity(i);
Toast.makeText(context, "Alarm triggered", Toast.LENGTH_LONG).show();
}
这个函数是我在AlarmReciever类中定义的唯一函数。
答案 0 :(得分:0)
您正在拨打
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
在onTimeChanged
侦听器中。这就是每次更改TimePicker时间时启动的原因。
您最好在视图中添加一个按钮,然后实施onClickListener
,您将从TimePicker中选择时间并在那里进行调用。