Ich habe eine einfache App zum Planen einer Benachrichtigung 5 Sekunden nach dem Drücken einer Taste gesehen. Aber was ich wirklich tun möchte, ist eine Benachrichtigung zu einem bestimmten Zeitpunkt zu planen (zB die Benachrichtigung wird um 00:00 Uhr angezeigt), aber ich weiß nicht wirklich wie ich diesen Moment einstellen soll (weil ich jetzt einen " verzögern"). Hier ist der Code:Zeitplan Benachrichtigung android
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_5:
scheduleNotification(getNotification("5 second delay"), 5000);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
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 = SystemClock.elapsedRealtime() + 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.mipmap.ic_launcher);
return builder.build();
}
}
Und die NotificationPublisher Klasse
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);
}
}
es noch besser wäre, wenn ich wüsste, wie die Benachrichtigung, um zu planen, dass eine Benachrichtigung um 00:00 Uhr
jeden Tag erscheint