如果活动被杀,AlarmManager不起作用

时间:2018-02-10 01:54:38

标签: android notifications android-service alarmmanager

我有一个AlarmManager使用来自用户输入的日历(存储在一个对象中),我的目标是从这个日历中安排通知,如果应用程序正在运行一切顺利,但是如果它被从最近的应用程序中删除了通知不来。我的代码是:

Intent intent = new Intent(getApplicationContext(), EventReciver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0, intent,0);

Calendar calendar = Calendar.getInstance();
Calendar horaInicial = materiaBuffer.getHoraInicial(); //Take Calendar from materiaBuffer object
calendar.set(Calendar.HOUR_OF_DAY, horaInicial.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, horaInicial.get(Calendar.MINUTE));

pendingIntent = PendingIntent.getBroadcast(this, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

在AndroidManifest中,我只需更改:

<receiver android:name=".etc.EventReciver" android:process=":remote"></receiver>

我的EventReciver:

public class EventReciver extends BroadcastReceiver{
  @Override
  public void onReceive(Context context, Intent intent) {
      Log.i("Lauri", "EventReciver");
      // I removed the code for the notification, it works fine
  }
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:-1)

我在Lolipop上测试过它。此代码工作正常,即使应用程序未运行

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 27);
calendar.set(Calendar.SECOND, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

maifest

<receiver
  android:name=".AlarmReceiver"
  android:enabled="true"
  android:exported="true" />

接收者类

public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    System.out.println("Alarm Received");
    Toast.makeText(context, "Alerm Received", Toast.LENGTH_SHORT).show();

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentTitle("Alarm")
            .setContentText("This code works!")
            .setAutoCancel(true);
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
 }
}