具有未来日期的android通知

时间:2015-12-11 09:43:57

标签: android notifications alarmmanager

我正在寻找一个解决方案,以生成通知,该通知将在生成通知后的5秒内显示。

为此,我找到了这个例子: https://gist.github.com/BrandonSmith/6679223

我的确如此,但我的应用中没有任何通知。 另一个“问题是”android studio告诉我,那个builder.build()需要api 16 - 但我必须使用min api 15

有人可以帮助我吗?

NotificationPublisher的

public class NotificationPublisher extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);

}
}

主要

public class Main extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        scheduleNotification(getNotification("5 second delay"), 5000);

    }


    private void scheduleNotification(Notification notification, int delay) {

        Intent notificationIntent = new Intent(this, NotificationPublisher.class);
        notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
        notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        long futureInMillis = System.currentTimeMillis() + delay;
        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    }

    private Notification getNotification(String content) {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("Scheduled Notification");
        builder.setContentText(content);
        builder.setSmallIcon(R.drawable.ic_notification_appicon);
        return builder.getNotification();
    }

}

1 个答案:

答案 0 :(得分:0)

您的代码与示例不同。以下一行:

long futureInMillis = System.currentTimeMillis() + delay;

应该是:

long futureInMillis = SystemClock.elapsedRealtime() + delay;