如何通过后台服务每天在android中的特定时间重复通知

问题描述 投票:23回答:2

嗨,我正在申请我已通过后台服务设置用户输入日期和时间的通知。现在我想在每天下午6点设置通知/闹钟,询问用户是否要添加其他条目?我怎样才能做到这一点?我应该使用相同的后台服务还是广播接收器?请给我更好的解决方案,教程将是个好主意。提前致谢。

android service broadcastreceiver alarm
2个回答
56
投票

首先将警报管理器设置如下

 Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.HOUR_OF_DAY, 18);
 calendar.set(Calendar.MINUTE, 30);
 calendar.set(Calendar.SECOND, 0);
 Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
 AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
 am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

在onReceive中创建广播接收器类“AlarmReceiver”会引发通知

public class AlarmReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, EVentsPerform.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(R.drawable.applogo)
                .setContentTitle("Alarm Fired")
                .setContentText("Events to be Performed").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
        notificationManager.notify(MID, mNotifyBuilder.build());
        MID++;

    }

}

并在清单文件中,注册AlarmReceiver类的接收器:

<receiver android:name=".AlarmReceiver"/>

通过警报管理器引发事件不需要特殊权限。


3
投票

N.V.Rao的回答是正确的,但不要忘记将receiver标记放在AndroidManifest.xml文件中的application标记内:

<receiver android:name=".alarm.AlarmReceiver" />
© www.soinside.com 2019 - 2024. All rights reserved.