没有发送android通知

时间:2013-11-19 07:53:18

标签: android notifications alarmmanager

我正在尝试在用户在datePicker上设置的那天向用户发送通知。

没有发送通知,我不知道为什么。

变量contextonReceive中定义为传递的上下文。

public void setAlarm() {
        int year = datePicker.getYear();
        int month = datePicker.getMonth();
        int day = datePicker.getDayOfMonth();

        Calendar c = Calendar.getInstance();
        c.set(year, month, day);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, NotifyReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        am.set(AlarmManager.RTC, c.getTimeInMillis(), pendingIntent);

        Toast.makeText(context, "Set reminder for: " + (month+1) + "/" + day + "/" + year, Toast.LENGTH_LONG).show();

    }

广播接收器:

public class NotifyReceiver extends BroadcastReceiver {

    private static final int NOTIFICATION = 12368327;

    private NotificationManager mNM;

    private Context context;

    @Override
    public void onReceive(Context ctx, Intent intent) {
        mNM = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        context = ctx;
        showNotification();
    }

    private void showNotification() {

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);

        Notification noti = new Notification.Builder(context)
                .setContentTitle("Title")
                .setContentText("Text").setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(contentIntent).build();

        // Clear the notification when it is pressed
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        // Send the notification to the system.
        mNM.notify(NOTIFICATION, noti);
    }
}

当调用方法意味着正在设置警报时,我也会得到祝酒词。

2 个答案:

答案 0 :(得分:1)

试试这一行

请设置您的AlarmManager

am .setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, 1000,pendingIntent_for_every_second);

由于

答案 1 :(得分:0)

您应该通过减少一个来传递“月”参数。

例如,如果您的月份是10月,那么您应该通过9而不是10

使用

c.set(year, month-1, day);

而不是

c.set(year, month, day);

无需使用set重复。