在特定时间发送通知

问题描述 投票:-7回答:2

例如,我需要在下午1点发送通知。我怎么能这样做并定期重复。

我需要使用“重复代码”实现此代码:

Intent intent = new Intent();

    PendingIntent pi = PendingIntent.getActivity(this, 0, intent , 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setTicker("Ticker Title")
            .setSmallIcon("icon")
            .setContentTitle("Notification Content Title")
            .setContentText("Output")
            .setContentIntent(pi)
            .setAutoCancel(true)
            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, notification);
android notifications
2个回答
0
投票
Intent myIntent = new Intent(this , NotifyService.class);     
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 12*60*60*1000 , pendingIntent);

使用通知服务和警报管理器,您可以执行所需的操作。


0
投票

使用警报管理器类启动您所需时间的意图。

AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 02);
calendar.set(Calendar.MINUTE, 00);

// setRepeating() lets you specify a precise custom interval--in this case,
// 1 day
alarmMgr.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis()/1000,
        AlarmManager.INTERVAL_DAY, alarmIntent);

在这里,您需要提供调用意图的时间。在我的代码中,它是每晚凌晨2点。此外,对于重复间隔,我选择了一天,因为我的过程需要每天调用。

© www.soinside.com 2019 - 2024. All rights reserved.