У меня возникла проблема с запуском службы из диспетчера аварийных сигналов.Служба Android не запускается из AlarmManager
Я создаю приложение, которое уведомляет владельца об именах своих друзей в facebook. Все работает хорошо, но уведомление не появится.
Я создали AlarmTask, который создает PendingIntent и устанавливает AlarmManager, как это:
public void run() {
// Request to start are service when the alarm date is upon us
Intent intent = new Intent(context, NotifyService.class);
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
intent.putExtra("notifyID", ID);
PendingIntent pendingIntent = PendingIntent.getService(context, ID, intent, 0);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
am.set(AlarmManager.RTC_WAKEUP, date.getTimeInMillis(), pendingIntent);
}
Идентификатор специфичен для каждого именины.
Теперь в моем NotifyService, я настроил эти:
@Override
public void onCreate() {
super.onCreate();
System.out.println("NOTIFICATION SERVICE onCreate()");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
System.out.println("INTENT RECIEVED: " + intent + " " + flags + " " + startId);
// If this service was started by out AlarmTask intent then we want to show our notification
if(intent.getBooleanExtra(INTENT_NOTIFY, false)){
int ID = intent.getIntExtra("notifyID", -1);
showNotification(ID);
}
// We don't care if this service is stopped as we have already delivered our notification
return START_STICKY;
}
Оба метода выполняются один раз, когда я запустить приложение, но когда уведомление должно прийти, ничего не происходит.
Есть ли способ проверить, действительно ли AlarmManager выполняет PendingIntent? Должен ли я использовать IntentService? Почему как?
Большое спасибо.
Я попытался изменить его BroadcastReciever, глядя, как это:
public class NotificationBroadcastReciever extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("BROADCAST RECIEVED");
}
}
Бит AlarmTask изменяется на это:
Intent intent = new Intent("NotificationBroadcast");
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
intent.putExtra("notifyID", ID);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), ID, intent, 0);
System.out.println("date for notification: " + date.get(Calendar.DAY_OF_MONTH) + "." + date.get(Calendar.MONTH) + "." + date.get(Calendar.YEAR));
System.out.println("epoch time in milils: " + date.getTimeInMillis());
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
am.set(AlarmManager.RTC_WAKEUP, date.getTimeInMillis(), pendingIntent);
и соответствующая манифеста часть выглядит следующим образом :
<receiver
android:name="cz.cvut.kubispe2.jmeniny.NotificationBroadcastReciever"
android:exported="false">
<intent-filter>
<action android:name="NotificationBroadcast" />
</intent-filter>
</receiver>
Я проверил, установлена ли дата, которая должна быть установлена, равным времени эпохи, и это все же, метод onRecieve никогда не вызывается.
Вы хотите добавить задержку в am.set()? date.getTimeInMillis() + DELAY_IN_MILLIS – yoah
Я пытаюсь запустить уведомление в указанную дату (здесь дата является экземпляром календаря с информацией об уведомлении), поэтому я не думаю, что потребуется задержка –
Из вашего описания , служба начинается с момента запуска приложения, которое похоже на то, что время сейчас или в прошлом, а не в будущем. В противном случае, почему служба запускается при запуске приложения? Добавьте сообщения журнала, ваш код выглядит нормально. – yoah