2015-01-05 2 views
2

У меня есть небольшая проблема с будильником, но я не смог найти ответ, который подходит для моего кода.AlarmManager не работает после закрытия приложения? - Android

Мой вопрос прост. У меня есть список тревог, который настроен на будущее. Пока мое приложение работает, я могу получить уведомление.

Но когда я закрываю свое приложение, оно не отправляет мне уведомление, и если я снова запустил приложение, то в уведомлении можно увидеть уведомления в прошлом.

Вот мои коды. В MainActivity.java Я использую этот метод, который может принимать список лиц и устанавливает тревогу каждого из Лица. Я бегу этот метод OnCreate()

private void createScheduledNotification(List<Person> people) 
{ 
    for(int i = 0; i<people.size();i++) { 

     // Get new calendar object 
     Calendar calendar = Calendar.getInstance(); 
     calendar.set(Calendar.MONTH, people.get(i).getMonth()); 
     calendar.set(Calendar.DAY_OF_MONTH, people.get(i).getDay()); 
     calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR)); 

     calendar.set(Calendar.HOUR_OF_DAY, people.get(i).getHour()); 
     calendar.set(Calendar.MINUTE, people.get(i).getMinute()); 
     calendar.set(Calendar.SECOND, 0); 

     // Retrieve alarm manager from the system 
     AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE); 
     // Every scheduled intent needs a different ID, else it is just executed once 
     int id = (int) System.currentTimeMillis(); 

     // Prepare the intent which should be launched at the date 
     Intent intent = new Intent(this, TimeAlarm.class); 
     intent.putExtra("person", people.get(i)); 
     // Prepare the pending intent 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

     // Register the alert in the system. You have the option to define if the device has to wake up on the alert or not 
     alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 
    } 
} 

И у меня есть класс, который проходит TimeAlarm BroadcastReciever.

public class TimeAlarm extends BroadcastReceiver { 

private Person person; 

@Override 
public void onReceive(Context context, Intent paramIntent) { 

    Bundle bundle = paramIntent.getExtras(); 
    person = (Person) bundle.getSerializable("person"); 
    // Request the notification manager 
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

    // Create a new intent which will be fired if you click on the notification 
    Intent intent = new Intent("android.intent.action.VIEW"); 

    // Attach the intent to a pending intent 
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

    // Create the notification 
    Notification notification = new Notification(R.drawable.logo24px, "Never Forget", System.currentTimeMillis()); 
    // 
    notification.setLatestEventInfo(context, "It's " + person.getName() + " " + person.getSname() + "'s Birthday!", "Celebrate his/her birthday! ",pendingIntent); 

    // Fire the notification 
    notificationManager.notify(1, notification); 
} 
} 

Также я добавляю эти строки в AndroidManifest.xml

 <receiver android:name=".TimeAlarm" > 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     </intent-filter> 
    </receiver> 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

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

ответ

2

Попробуйте использовать это при создании намерения

Bundle extras = new Bundle(); 
extras.putSerializable("person", people.get(i)); 
intent.putExtras(extras);  

И в чеке BroadcastReciver, если действие башмак завершено действие. (это может быть и ваша тревога).

@Override 
public void onReceive(Context context, Intent paramIntent) { 
        //CHECK IF IS BOOT COPLETED 
       if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { 
          /* Setting the alarm here Alarm are automatically cleaned on phone shutdown*/} 
       else{ 
         Bundle bundle = paramIntent.getExtras(); 
         person = (Person) bundle.getSerializable("person"); 
         // Request the notification manager 
         NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

         // Create a new intent which will be fired if you click on the notification 
         Intent intent = new Intent("android.intent.action.VIEW"); 

         // Attach the intent to a pending intent 
         PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

         // Create the notification 
         Notification notification = new Notification(R.drawable.logo24px, "Never Forget", System.currentTimeMillis()); 
         // 
         notification.setLatestEventInfo(context, "It's " + person.getName() + " " + person.getSname() + "'s Birthday!", "Celebrate his/her birthday! ",pendingIntent); 

         // Fire the notification 
         notificationManager.notify(1, notification);} 
        } 
    } 

Также проверьте этот

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

, потому что кажется, что вы continusly обновление же намерения, является то, что вы хотите?

Edit:

К сожалению, я не помню, чтобы вставить его, ваше заявление sholuld приемник быть.

<receiver android:name=".TimeAlarm" 
     android:process=":remote" 
     android:enabled="true" 
     android:exported="true"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     </intent-filter> 
    </receiver> 
Смежные вопросы