2014-01-07 3 views
1

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

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"/> 

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

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

EDIT

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

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

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

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

+0

В чем проблема? – Hardik

+0

ничего не отображается, ничего не происходит – theForgottenCoder

+0

Почему вы используете широковещательный приемник здесь, вы хотите начать сервис во время загрузки? – Hardik

ответ

0

попробуйте это, замените ваши широкие полосы т приемник класса для обслуживания `

(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); 

EDIT

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, 
       System.currentTimeMillis(), 5000, pendingIntent); 
+0

как и и Сатьяки Мукерджи был таким же ответ, но никто не работал :( – theForgottenCoder

+0

см моего отредактированный ответ – Hardik

+0

у меня задержка 5 секунд (5000) он должен стрелять каждые 5 секунд – Hardik

0

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

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 

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

+0

AlarmManager alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE); \t \t alarmManager.setRepeating (AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, 5000, pendingIntent); Я пытался что без толка – theForgottenCoder

0

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

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.класса по следующему коду:

@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; 

    } 

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

+0

Я понял, что вы имеете в виду, я сделал измененный, но все еще ничего не придумал :( – theForgottenCoder

+0

Прежде чем я дам вам код, который я проверил на устройстве. Так что, извините, я понятия не имею больше чем это. –

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