android 条未来日期的通知

android notifications with a future date

我正在寻找一个解决方案,以生成一个通知,例如在生成通知后 5 秒显示。

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

我完全是这样做的,但我的应用程序中不会激活任何通知。 android 工作室告诉我的另一个 "problem is",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();
    }

}

您的代码与示例不一样。下面一行:

long futureInMillis = System.currentTimeMillis() + delay;

应该是:

long futureInMillis = SystemClock.elapsedRealtime() + delay;