每日通知-Android Studio

时间:2018-10-21 08:26:44

标签: java android

我正在开发一个Android应用程序,我想每天在既定时间添加一条通知,但是每次进入该应用程序时我都会收到通知。

这是我的AlarmReceiver.java

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, MainActivity.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.mipmap.ic_launcher_rp_round)
            .setBadgeIconType ( R.mipmap.ic_launcher_rp_round )
            .setContentTitle("Title")
            .setContentText("Text").setSound(alarmSound)
            .setAutoCancel(true).setWhen(when)
            .setContentIntent(pendingIntent)
            .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
    notificationManager.notify(0, mNotifyBuilder.build());
}

和主要活动中:

    private void registerAlarm()
{
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 10);
    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);

}

请帮助我:D

0 个答案:

没有答案