一段时间后重复通知

时间:2016-09-05 04:23:52

标签: android

我想创建一个通知,它可以在一段时间后重复 这是我的代码 NotifyService.class

public class NotifyService extends Service {
private NotificationManager mNotificationManager;
private Context ctx;
private PendingIntent contentIntent;
@Override
public void onCreate() {
    super.onCreate();
    ctx=this;
    sendNotificationCmt();
}
private void sendNotificationCmt() {
    mNotificationManager = (NotificationManager)
            ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent in = new Intent(ctx, MainActivity.class);
    contentIntent = PendingIntent.getActivity(ctx, 0, in, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(ctx)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("hello")
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText("des"))
                    .setContentText("des1");

    mBuilder.setContentIntent(contentIntent);
    mBuilder.setAutoCancel(true);
    mNotificationManager.notify(2712, mBuilder.build());
}


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

在MainActivity.class中,我调用了:

Intent notificationIntent = new Intent(this, NotifyService.class);
    PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.cancel(contentIntent);
    am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(),
                2 * 60 * 60, contentIntent);

在AndroidManifest中我添加了:

<service android:name="NotifyService"/>

但不重复,这里发生了什么,请帮助我。非常感谢

1 个答案:

答案 0 :(得分:0)

您的代码中的问题是您在MainActivity中设置了一个警报,当关闭时会收集垃圾。您设置的只有一个警报正在运行。

Google提供了完整的警报教程。检查此链接:

https://developer.android.com/training/scheduling/alarms.html