AlarmReceiver中的Android通知

时间:2012-02-18 17:18:15

标签: android notifications alarmmanager

我希望能够创建一个警报,通知用户每2分钟启动一次应用程序。一切正常,但是当我手动启动我的应用程序时会出现通知。这是我的代码:

接收器:

public void onReceive(Context context, Intent intent) {
    nm = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    CharSequence from = "myactivity";
    CharSequence message = "click to start activity";


    Intent scheduledIntent = new Intent(context, AmslerTestActivity.class);


    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            scheduledIntent, 0);
    Notification notif = new Notification(R.drawable.icon,
            message, System.currentTimeMillis());
    notif.setLatestEventInfo(context, from, message, contentIntent);
    notif.flags = Notification.FLAG_AUTO_CANCEL;
    notif.defaults |= Notification.DEFAULT_SOUND;
    nm.notify(1, notif);
    scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(scheduledIntent);

}

调度程序:

cal.set(Calendar.HOUR_OF_DAY, 12);
    cal.set(Calendar.MINUTE, 01);
    cal.set(Calendar.SECOND, 0);

    Intent intent = new Intent(myactivity.this, AlarmReceiver.class);

    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    // Get the AlarmManager service
    am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 2 * 60 * 1000, sender);

我希望通知仅在代码未运行时响铃。

1 个答案:

答案 0 :(得分:0)

将代码中的“计划程序”部分放在onPauseonStoponDestroy中,以便仅在Activity停止后设置警报。阅读here以确定最适合您的目的。然后,在执行am.setRepeating时,对System.currentTimeMillis() + 2 * 60 * 1000使用triggerAtTime,以便在Activity停止后2分钟触发警报。然后它将根据您当前正确设置为2分钟的第3个参数interval每2分钟重复一次。