Android Set Event с помощью Alarm Manager?

Я пытаюсь создать событие напоминания, которое будет отображать уведомление в определенное время в моем приложении, ради этого примера я установил экземпляр Calendar на одну минуту до текущего времени. Это мой код appointment.java, здесь экземпляр Calendar инициализируется текущим временем + одна минута для этого примера.

Calendar ctest = Calendar.getInstance();
ctest.add(Calendar.MINUTE, 1);
Intent myIntent = new Intent(Appointments.this, AlarmRec.class);
pendingIntent = PendingIntent.getBroadcast(Appointments.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, ctest.getTimeInMillis(), pendingIntent);

Затем у меня есть следующий код в моем AlarmRec.class, который действует как BroadcastReceiver.

public class AlarmRec extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {  
        Intent service1 = new Intent(context, MyAlarmService.class);
        context.startService(service1);
    }
}

Затем, наконец, в моем MyAlarmService.class у меня есть следующее

public void onStart(Intent intent, int startId)
{
   super.onStart(intent, startId);

   mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
   Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

   Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
   intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

   PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
   notification.flags |= Notification.FLAG_AUTO_CANCEL;
   notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

   mManager.notify(0, notification);
}

и мой AndroidManifest содержит

  <service android:name=".MyAlarmService"
             android:enabled="true" />

    <receiver android:name=".AlarmRec"/>

проблема, с которой я сталкиваюсь, заключается в том, что ничего не отображается, никаких уведомлений или чего-то еще, поэтому я не уверен, что делаю что-то не так

Также, если я допустил ошибки в своем сообщении, пожалуйста, потерпите меня, если я допустил ошибки с форматированием вопроса.

РЕДАКТИРОВАТЬ

вау решил, спасибо за помощь, ребята, избавился от широковещательного приемника и просто воспользовался сервисом, хотя в конце он все еще не работал, я понял, что у меня небольшая опечатка в моем манифесте Android

<service android:name=".MyAlarmService" android:enabled="true" />

Если вы видите, что я забыл указать имя пакета для службы, оно должно было быть myCF.MyAlarmService

Спасибо за помощь всем, я очень ценю это


person theForgottenCoder    schedule 07.01.2014    source источник
comment
в чем дело?   -  person Hardik    schedule 07.01.2014
comment
уведомление не отображается, на самом деле ничего не происходит   -  person theForgottenCoder    schedule 07.01.2014
comment
почему вы используете широковещательный приемник здесь, вы хотите запустить службу во время загрузки?   -  person Hardik    schedule 07.01.2014
comment
ммм, я хочу запустить службу в любое время после того, как назначена встреча, если я настрою слишком 10 минут, она должна дать мне уведомление, и если я сделаю это через 3 дня и в это время, если я перезагрузлю свой телефон, он все равно должен дать мне уведомление. вещательный ресивер не лучший вариант в данном случае?   -  person theForgottenCoder    schedule 07.01.2014
comment
тогда вам не нужен широковещательный приемник   -  person Hardik    schedule 07.01.2014


Ответы (4)


попробуйте это, замените класс вашего широковещательного приемника на сервис `

(AlarmRec.class===> MyAlarmService.class))`

Calendar ctest = Calendar.getInstance();
        ctest.add(Calendar.MINUTE, 1);
         Intent myIntent = new Intent(Appointments.this, MyAlarmService.class);
          pendingIntent = PendingIntent.getBroadcast(Appointments.this, 0, myIntent,0);
         AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

РЕДАКТИРОВАТЬ

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(), 5000, pendingIntent);
person Hardik    schedule 07.01.2014
comment
и у вас, и у Сатьяки Мукерджи был один и тот же ответ, но ни один из них не работал :( - person theForgottenCoder; 07.01.2014
comment
у меня задержка 5 секунд (5000) она должна срабатывать каждые 5 секунд - person Hardik; 07.01.2014
comment
попробовал, все равно не работает :( может быть, это мой эмулятор, позвольте мне установить его на моем устройстве - person theForgottenCoder; 07.01.2014

Пожалуйста, следуйте следующему коду:

long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis * DateUtils.MINUTE_IN_MILLIS;
Maybe you meant for the alarm to go off in one minute:

long nextUpdateTimeMillis = currentTimeMillis + DateUtils.MINUTE_IN_MILLIS;
Anyway first use:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
                          System.currentTimeMillis() + 10000, 
                          5000,
                          pendingIntent);
To confirm your setup is correct, if so you need to recalculate your nextUpdateTimeMillis

Предоставлено Сэмом https://stackoverflow.com/a/13593926/1465910

person Name is Nilay    schedule 07.01.2014
comment
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, 5000, pendingIntent); Я пробовал это безрезультатно - person theForgottenCoder; 07.01.2014

Вам необходимо зарегистрировать трансляцию в своей службе, как показано ниже: зарегистрировать приемник в службе

person goofyz    schedule 07.01.2014

Вызовите службу из Activity, потому что получатель не нужен:

Calendar ctest = Calendar.getInstance();
    ctest.add(Calendar.MINUTE, 1);
     Intent myIntent = new Intent(Appointments.this, MyAlarmService.class);
      pendingIntent = PendingIntent.getBroadcast(Appointments.this, 0, myIntent,0);
     AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, ctest.getTimeInMillis(), pendingIntent);
startService(myIntent );

После этого измените свой MyAlarmService.class следующим кодом:

    @Override   
    public void onCreate() 
    {   
      super.onCreate(); 

    }

    @Override   
    public int onStartCommand(Intent intent, int flags, int startId) 
    {   


        NotificationManager mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
           Intent intent1 = new Intent(this.getApplicationContext(),MainActivity1.class);

           Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
           intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

           PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
           notification.flags |= Notification.FLAG_AUTO_CANCEL;
           notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

           mManager.notify(0, notification);
        return 0;

    }

Это сработает. попробуйте это и дайте мне знать.

person Satyaki Mukherjee    schedule 07.01.2014
comment
Я понимаю, что вы имеете в виду, я внес изменения, но все равно ничего не происходит :( - person theForgottenCoder; 07.01.2014
comment
Прежде чем дать вам код, я протестировал его на устройстве. Так что, извините, я понятия не имею больше, чем это. - person Satyaki Mukherjee; 07.01.2014