java - Android 闹钟管理器不会等待

标签 java android notifications alarmmanager

我尝试每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/

相关文章:

java - MongoDB Java 查询 : Pattern. 编译(文本)(类似于 '%' 的 SQL)结果

android - 如何从后台服务将 Activity 带到前台

android - 在 pjsip 中成功编译 android 后尝试构建 libpjsua2.so 文件时目标不兼容

android - 使用公式 px = dp * (dpi/160) 创建图像资源不会产生清晰的图像

ASP.NET MVC + SQL Server 应用程序 : Best Way to Send Out Event-Driven E-mail Notifications

java - 使用可变键解析 json

java - 无法在spring + maven + tomcat中启动配置文件

Android/阅读所有 Activity 状态栏通知

Android BroadcastReceiver 设置闹钟

java - java swing中的简单可滚动文本区域