我需要在某个时间间隔内设置闹钟。为了实现它,我写道:
private void setupAlarmManager(){
AlarmManager manager = manager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(getContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), i, alarmIntent, PendingIntent.FLAG_ONE_SHOT);
manager.set(AlarmManager.RTC_WAKEUP,1499510100000L, pendingIntent);
manager.set(AlarmManager.RTC_WAKEUP,1499510220000L, pendingIntent);
}
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
我把调试点放在Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
但没有发生任何事情。
下午4点= 1499510100000L
下午4:03 = 1499510220000L
我在这里做错了什么?此外,我想在onReceive
方法中添加本地通知。
答案 0 :(得分:1)
您应该使用Calendar
对象来设置闹钟时间。
对于下午4点的闹钟,您可以执行以下操作:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND,0);
然后您按照惯例设置AlarmManager
,但最后一行使用:
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
也许您想要使用重复闹钟甚至是Handler
如果是这样,您应该访问:https://developer.android.com/training/scheduling/alarms.html