使用AlarmManager在特定时间显示通知

时间:2014-09-25 11:15:19

标签: android android-notifications android-alarms

我需要在特定时间每天显示通知(例如:4.25PM)。我正在使用AlarmManagerNotification。我在应用程序的登录页面上设置了警报。我也为它实现了BroadcastReceiver

设置闹钟的代码:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 25);
calendar.set(Calendar.SECOND, 0);

Intent notificationmassage = new Intent(getApplicationContext(),Notificationmassage.class);

//This is alarm manager
PendingIntent pi = PendingIntent.getService(this, 0 , notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, pi);

这是广播接收器

public class Notificationmassage extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        showNotification(context);
    }

    private void showNotification(Context context) {
        Log.i("notification", "visible");

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

        NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("xyz")
                .setContentText("It will contain dummy content");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }  
}

这种方法有什么问题?

1 个答案:

答案 0 :(得分:4)

如果您之前不这样做,请将接收器添加到Manifest.xml。

 <receiver android:name="org.yourapp.Notificationmassage"></receiver>

在申请部分

    <application>
       ....

       <receiver android:name="org.yourapp.Notificationmassage"></receiver>

    </application>

如果您已经这样做,请编辑您的问题并显示您的Manifest.xml