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

标签 android service broadcastreceiver alarm

您好,我正在开发应用程序,在该应用程序中我通过后台服务设置了用户输入日期和时间的通知。现在我想在每天下午 6 点设置通知/警报,询问用户是否要添加另一个条目? 我怎样才能做到这一点?我应该使用相同的后台服务还是广播接收器? 请为此提供更好的解决方案,教程将是个好主意。 提前致谢。

最佳答案

首先如下设置报警管理器

 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);

在此创建一个广播接收器类“AlarmReceiver” onReceive 时的通知

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++;

    }

}

并在 list 文件中,为 AlarmReceiver 类注册接收器:

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

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

关于android - 如何通过后台服务在android中的特定时间每天重复通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23440251/

相关文章:

android - 如何在选项卡 Activity 中将选项卡放在应用程序底部

java - 现在在哪里可以找到AndroidObservable.fromBroadcast?

android - 如何设置闹钟在固定时间正确触发?

android - 是否可以在线构建 Cordova 应用程序?

android - SoftInput.AdjustResize 导致键盘在显示或隐藏时闪烁

python - python 和 upnp 中的库

service - 有哪些服务可以根据 IP 对个人进行地理定位?

service - kubernetes服务何时支持基于集合的选择器?

安卓开发 : How I can find the list of all avaiable intent-filter actions for a receiver?

java - 回显 TextView 的内容?