我尝试每20秒启动一个简单的方法,我的想法是在这个方法中再次启动一个闹钟。再次创建此类,其中执行该方法并启动另一个警报...等等 该方法本身应该创建一个通知。
public class CreateNotification extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
doStuff();
NotificationCompat.Builder mNoteBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
.setContentTitle("...")
.setContentText(shownString)
//get an instance of the notificationManager service
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//build the notification
mNotifyMgr.notify(mNotificationID, mNoteBuilder.build());
createNewAlarm(context);
}
private void createNewAlarm(Context context){
Intent alarmIntent = new Intent(context, CreateNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP, 20000, pendingIntent);
}
}
这是在我的主要 Activity 中开始的:
Intent alarmIntent = new Intent(this, CreateNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP, 4000, pendingIntent);
现在我的问题是,我没有得到预期的结果,即每 20 秒一个新的通知,但它会以处理器允许的速度创建所有时间通知。中间没有中断,并且 Alarmmanager 似乎没有安排任何内容,而只是立即创建类。
非常感谢您的帮助!
最佳答案
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+20000, pendingIntent);
您的解决方案:20000 = 1970. 1 月 1. 0:00:20 所以你必须将毫秒添加到当前时间。 (获取当前时间的另一种解决方案。)
Calendar calendar = Calendar.getInstance();
calendar.getTimeInMillis()+yourTimeInMillis;
关于java - Android 闹钟管理器不会等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33284390/