#android #notifications
#Android #уведомления
Вопрос:
У меня есть общедоступный класс для создания уведомлений…
public class notifyHelper {
public void sendNotification(Activity caller, Class<?> activityToLaunch, String title, String msg, int numberOfEvents, boolean flashLed, boolean vibrate, int ID) {
NotificationManager notifier = (NotificationManager) caller.getSystemService(Context.NOTIFICATION_SERVICE);
// Create this outside the button so we can increment the number drawn over the notification icon.
// This indicates the number of alerts for this event.
long whenTo = System.currentTimeMillis() (1000 * 60 * 15);
final Notification notify = new Notification(R.drawable.icon, "", whenTo);
notify.icon = R.drawable.icon;
notify.tickerText = "TV Spored ";
notify.when = whenTo;
notify.number = numberOfEvents;
notify.flags |= Notification.FLAG_AUTO_CANCEL;
if (flashLed) {
// add lights
notify.flags |= Notification.FLAG_SHOW_LIGHTS;
notify.ledARGB = Color.CYAN;
notify.ledOnMS = 500;
notify.ledOffMS = 500;
notify.defaults |= Notification.DEFAULT_SOUND;
}
if (vibrate) {
notify.vibrate = new long[] {100, 200, 200, 200, 200, 200, 1000, 200, 200, 200, 1000, 200};
}
Intent toLaunch = new Intent(caller, activityToLaunch);
PendingIntent intentBack = PendingIntent.getActivity(caller, 0, toLaunch, 0);
notify.setLatestEventInfo(caller, title, msg, intentBack);
notifier.notify(ID, notify);
}
public static void clear(Activity caller) {
NotificationManager notifier = (NotificationManager) caller.getSystemService(Context.NOTIFICATION_SERVICE);
notifier.cancelAll();
}
}
Независимо от того, что я делаю (смотрю whenTo), это уведомление всегда отображается при вызове… Как я могу установить время уведомления?
Спасибо за ответ!
Ответ №1:
Что заставляет вас думать, что есть способ создать уведомление, которое не является немедленным?
От http://developer.android.com/reference/android/app/Notification.html вы можете увидеть несколько важных вещей. Во-первых, используемый вами конструктор устарел — вам следует подумать об использовании http://developer.android.com/reference/android/app/Notification .Builder.html вместо этого. Что еще более важно, 3-й параметр — это не «когда показывать уведомление», это время для отображения в поле time самого уведомления. Чтобы визуализировать это … позвоните на свой телефон и не отвечайте (чтобы вызвать уведомление о пропущенном вызове). Затем опустите панель уведомлений и обратите внимание на время, которое отображается в правом нижнем углу.
Комментарии:
1. Спасибо за ответ… Как насчет уведомлений, как во многих приложениях… Уведомления, подобные календарю… Что я хочу сделать, так это создать напоминание о чем-то в будущем (скажем, на завтра в 10 утра)…
2. @M.V. — Вы не отправляете уведомление, пока оно не будет готово для просмотра. Я бы предположил, что большинство приложений управляют этим с помощью AlarmManager, запуск которого запланирован на момент следующего уведомления; в это время они отправляют уведомление, а также определяют, когда будет следующее, и устанавливают новую запись AlarmManager.
Ответ №2:
может быть, это поможет вам
private void createNotification(String contentTitle, String contentText, String tickerText, long millisec){
notificationManager = (NotificationManager) this.ctx.getSystemService(Context.NOTIFICATION_SERVICE);
note = new Notification(android.R.drawable.btn_star_big_on, tickerText, millisec );
note.when = millisec;
Intent notificationIntent = new Intent(this.ctx, CenteringActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
contentIntent = PendingIntent.getActivity(this.ctx, 0, notificationIntent, 0);
note.setLatestEventInfo(this.ctx, contentTitle, contentText, contentIntent);
note.number = 1;//Just created notification so number=1. Remove this line if you don't want numbers
notificationManager.notify(notif_ID, note);
}
private void createStatusBarNotification(final String contentTitle, final String contentText, final String tickerText, final long millisec)
{
//Date date = new Date(System.currentTimeMillis() (1000 * 60 * 2));
//long f = System.currentTimeMillis() (1000 * 60 * 2);
//super.webView.loadUrl("javascript: alert('::" millisec "," f "')");
Date date = new Date(millisec);
Timer timer = new Timer();
TimerTask timerTask = new TimerTask(){
@Override
public void run(){
createNotification( contentTitle, contentText, tickerText, millisec);
}
};
timer.schedule(timerTask, date, 1000*60);//(1000*60)will repeate the same notification in 1 minute
}
Ответ №3:
Вы должны использовать AlarmManager, чтобы запланировать уведомление.