设置Alarm Manager Android

时间:2016-02-18 09:51:02

标签: android alarmmanager

我一直在尝试设置一个警报管理器,但我似乎无法让它工作。

我的AlertManager如下:

    public class AlertReceiver extends BroadcastReceiver{
    private static final long REPEAT_TIME = 1000 * 30;
    @Override
    public void onReceive(Context context, Intent intent) {

      AlarmManager service = (AlarmManager) context
      .getSystemService(Context.ALARM_SERVICE);
      Intent i = new Intent(context, MainActivity.class);
      PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent,
      PendingIntent.FLAG_CANCEL_CURRENT);
      Calendar cal = Calendar.getInstance();

      cal.add(Calendar.SECOND, 30);
    // InexactRepeating allows Android to optimize the energy consumption
      service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
       cal.getTimeInMillis(), REPEAT_TIME, pending);
     } 

AlertManager中的CreateNotification方法:

      public void createNotification(Context context, String msg, String  msgText, String msgAlert) {

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

      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
        .setContentTitle(msg)
        .setTicker(msgAlert)
        .setContentText(msgText);

       mBuilder.setContentIntent(notificationIntent);
       mBuilder.setDefaults(NotificationCompat.DEFAULT_LIGHTS);
       mBuilder.setAutoCancel(true);

       NotificationManager notificationManager = (NotificationManager)
        context.getSystemService(Context.NOTIFICATION_SERVICE);
       notificationManager.notify(1, mBuilder.build());
        }

我的主要活动如下:showNotification方法,它位于onCreate:

之外
     public void showNotification(View view) {
        NotificationCompat.Builder notificBuilder = new        NotificationCompat.Builder(this)
.setContentTitle("message")
.setContentText("New Message")
.setTicker("Alert New Message");

  Intent moreInfoIntent = new Intent(this, MoreInfoNotification.class);

  TaskStackBuilder tStackBuilder = TaskStackBuilder.create(this);

tStackBuilder.addParentStack(MoreInfoNotification.class);

  tStackBuilder.addNextIntent(moreInfoIntent);

    PendingIntent pendingIntent = tStackBuilder.getPendingIntent(0,    PendingIntent.FLAG_UPDATE_CURRENT);

    notificBuilder.setContentIntent(pendingIntent);


      notificationManager =        (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);        
notificationManager.notify(notifId, notificBuilder.build());

   isNotificActive = true;
      }

1 个答案:

答案 0 :(得分:0)

在您的代码中:

Intent i = new Intent(context, MainActivity.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);

我想你想开始MainActivity,但你创建了一个PendingIntent来发送一个Boardcast消息(通过getBroadcast()方法)。您应该使用getActivity()的{​​{1}}方法。