9

Я ищу в течение нескольких часов, как делать это точно:Android уведомления во время

Я хочу, чтобы каждый день (кроме выходных) уведомление отправляется в то время (скажем, 18:00 (= 6 вечера)) за исключением случаев, когда приложение уже открыто. Это похоже на приложение gmail, когда вы получаете почту. Когда пользователь нажимает уведомление, он должен исчезнуть и должен быть доставлен в MainActivity.

Я пробовал много вещей с помощью AlarmManager, но ни одно из них не привело к появлению уведомления.

Код я пытался, что я чувствую себя довольно близко к правильным, заключается в следующем: В моей MainActivity:

AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE); 
Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.HOUR_OF_DAY, 18); 
Intent intent = new Intent(this, NotificationService.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); 
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 

Мой NotificationService:

public class NotificationService extends IntentService { 



    public NotificationService() { 
     super("NotificationService"); 
    } 

    @Override 
    @SuppressWarnings("deprecation") 
    protected void onHandleIntent(Intent intent) { 
     NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
     Notification notification = new Notification(R.drawable.ic_launcher, "reminder", System.currentTimeMillis()); 
     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     Intent notificationIntent = new Intent(this, MainActivity.class); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent , 0); 
     notification.setLatestEventInfo(getApplicationContext(), "It's about time", "You should open the app now", contentIntent); 
     nm.notify(1, notification); 
    } 
} 

Примечание Я использую устаревший материал, потому что это был даже единственный способ получения уведомления, когда он не работал с AlarmManager. Если возможно, ответьте на это решение, в котором нет устаревшего материала, но с обновленным материалом: P.

Многое много спасибо заранее!

сердечным приветом

ответ

10

Наконец мне удалось найти решение:

private void handleNotification() { 
    Intent alarmIntent = new Intent(this, AlarmReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5000, pendingIntent); 
} 

Это мой обычай BroadcastReceiver:

public class AlarmReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Calendar now = GregorianCalendar.getInstance(); 
     int dayOfWeek = now.get(Calendar.DATE); 
     if(dayOfWeek != 1 && dayOfWeek != 7) { 
      NotificationCompat.Builder mBuilder = 
        new NotificationCompat.Builder(context) 
        .setSmallIcon(R.drawable.ic_launcher) 
        .setContentTitle(context.getResources().getString(R.string.message_box_title)) 
        .setContentText(context.getResources().getString(R.string.message_timesheet_not_up_to_date)); 
      Intent resultIntent = new Intent(context, MainActivity.class); 
      TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 
      stackBuilder.addParentStack(MainActivity.class); 
      stackBuilder.addNextIntent(resultIntent); 
      PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 
      mBuilder.setContentIntent(resultPendingIntent); 
      NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      mNotificationManager.notify(1, mBuilder.build()); 
     } 
    } 
} 

И это в манифесте в теге приложения:

<receiver 
     android:name="be.menis.timesheet.service.AlarmReceiver" 
     android:process=":remote" /> 
+0

что это за 'android: name =" be.menis.timesheet.service.AlarmReceiver "' ?? Я хочу настроить уведомление в 10:00 ежедневно – Neo

+0

@ashish, который является именем пакета приложения и местоположением получателя –

+0

Спасибо за код, сейчас я тестирую его. Но кто-нибудь знает, буду ли я устанавливать новый сигнал тревоги каждый раз, когда я запускаю этот код? если это так, я должен быть очень осторожен с этим ... – George

Смежные вопросы