Android 未显示未来通知

Android Future Notification Not Showing

我希望我的应用每天通知用户,我正在使用 AlarmManager 来实现它。但是,通知没有显示。另外,我没有任何错误或异常。

这是我设置AlarmManager的部分代码(测试的重复间隔是1000ms,我会在实际程序中更改):

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        Intent intent1 = new Intent(this, Notify.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000, pendingIntent);

这是 Notify class 中的 onReceive(),它扩展了 BroadcastReceiver:

  public void onReceive(Context context, Intent intent) {
    NotificationCompat.Builder n=new NotificationCompat.Builder(context);
    n.setAutoCancel(true);
    n.setSmallIcon(R.mipmap.ic_launcher);
    n.setTicker("ticker");
    n.setWhen(System.currentTimeMillis());
    n.setContentTitle("title");
    n.setContentText("text");
    Intent it=new Intent(context,ListAll.class);
    PendingIntent pi=PendingIntent.getBroadcast(context,0, it,0);
    n.setContentIntent(pi);
    ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(uniqueID,n.build());
  }

并且我在 Manifest.xml 中添加了以下内容:

   <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
   <receiver android:name=".Notify" android:process=":remote" />

我很确定您用户的设备根本不需要重启,否则您的闹钟将消失,除非他们重新启动您的应用,并且您的应用知道再次设置闹钟。

找到的文档:

By default, all alarms are canceled when a device shuts down. To prevent this from happening, you can design your application to automatically restart a repeating alarm if the user reboots the device. This ensures that the AlarmManager will continue doing its task without the user needing to manually restart the alarm.

来自 http://developer.android.com/training/scheduling/alarms.html 页面


您正在设置警报 every 1 second 这可能是问题所在,如果内部代码会像那样丢弃警报,我不会感到惊讶。 (为了设备的完整性+电池)


来自此处的示例:http://developer.android.com/training/scheduling/alarms.html#set 您缺少这样的行,您设置 'what time' 警报应该响起。

当您告诉闹钟管理器设置重复闹钟时,calendar.setTimeInMillis(System.currentTimeMillis()); 中的 'time' 已经过去了。因此,我不确定它会给你带来什么行为,但它可能是你收到的不受欢迎的行为。尝试在 5 分钟内将闹钟告诉 'go off',并且每 20 分钟重复一次。 (如指南中的示例)。看看是否有帮助。

calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);

我认为您将 AlarmManager 与 AlarmClock 混为一谈。

https://developer.android.com/reference/android/app/AlarmManager.html

https://developer.android.com/reference/android/provider/AlarmClock.html


我认为您根本不需要 <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>,因为您不是在编写闹钟应用程序。你只想 'use' 报警。

This guide Should help you tiny up your code. Because you will need to set a broadcast receiver to be notified on android.permission.RECIEVE_BOOT_COMPLETED 这有关于如何做到这一点的代码。 (每次 phone 重启时 'restart' 你的闹钟)