1

Мне нужно отправить уведомления с фона, даже если пользователь удалил приложение из ОЗУ, получив информацию (чтобы добавить уведомление) в качестве дополнительных функций из намерений.Android: нажмите динамические уведомления с фона, пока приложение закрыто.

В настоящее время он работает, если приложение открыто или открыто в фоновом режиме, но оно не может быть добавлено, когда приложение закрыто из последних приложений (удалено из ОЗУ).

Это действие, которое создает фоновое обслуживание и помещает идентификатор, который мне нужно передать как Экстра.

AddEvent.java

// Gets the ID after it was generated by the database 
     int ID = newEvent.getID(); 

     if (newEvent.hasNotification()) { 
      // Creates the intent that starts the background service 
      Intent serviceIntent = new Intent(this, NotificationService.class); 

      // Puts the ID and the Notification Time as Extras and starts the service 
      serviceIntent.putExtra(EXTRA_NOTIFICATION_ID,ID); 
      serviceIntent.putExtra(EXTRA_NOTIFICATION_TIME,notificationDate.getTimeInMillis()); 
      startService(serviceIntent); 
     } 

Эта деятельность начинает IntentService, что я продлен.

NotificationService.java

public class NotificationService extends IntentService { 

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

@Override 
protected void onHandleIntent(Intent workIntent) { 

    // Create the intent that is going to push the notification, giving it the previous bundle 
    Intent notificationIntent = new Intent(this, NotificationPusher.class); 

    long notificationTime = workIntent.getLongExtra(ActivityAddEvent.EXTRA_NOTIFICATION_TIME,-1); 
    int ID = workIntent.getIntExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID,-1); 
    Log.d("ID Service",""+ID); 
    notificationIntent.putExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID,ID); 

    PendingIntent pusher = PendingIntent.getBroadcast(this, UniqueID.getUniqueID(), 
      notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    //TODO : Can't get the Extras in Pusher 

    // Sets the alarm for the designed date and time 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    alarmManager.set(AlarmManager.RTC_WAKEUP,notificationTime,pusher); 
} 

public static class UniqueID { 
    private final static AtomicInteger uniqueID = new AtomicInteger(0); 
    public static int getUniqueID() { 
     return uniqueID.incrementAndGet(); 
    } 
} 

}

Он получает время notitication и устанавливает его в диспетчере сигнализации, чтобы подтолкнуть уведомления в нужное время.

Идентификатор и время (как долго) затем помещает идентификатор в новое намерение, которое является уведомляющим толкателем, который выдает уведомление.

NotificationPusher.java

public class NotificationPusher extends BroadcastReceiver { 

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

    // Gets the event from the database using the ID received in the intent 
    int ID = workIntent.getIntExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID, -1); 
    Log.d("ID Pusher", "" + ID); 


    EventManager eventManager = EventManager.getInstance(context); 
    Event event = null; 
    try { 
     event = eventManager.getEvent(ID); 
    } catch (SQLException e) { 
     // TODO: Add error for id not found 
     e.printStackTrace(); 
    } 

    if (event != null) { 
     String notificationTitle; 
     String notificationText; 
     // Sets the notification 
     if (event.hasSubject()) { 
      notificationTitle = event.getSubject() + "'s " + event.getType().toString(); 
      notificationText = context.getString(R.string.event_notification_default_text); 
     } else { 
      notificationTitle = event.getType().toString(); 
      notificationText = event.getTitle(); 
     } 

     // Create the intent that is gonna be triggered when the notification is clicked and add to the stack 
     Intent notificationIntent = new Intent(context, ActivitySingleEvent.class); 
     notificationIntent.putExtra(ActivityAddEvent.EXTRA_NOTIFICATION_ID, ID); 

     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
       Intent.FLAG_ACTIVITY_CLEAR_TASK); 

     PendingIntent pendingIntent = PendingIntent.getActivity(context, NotificationService.UniqueID.getUniqueID(), 
       notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

     // Gets the default sound for notifications 
     Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

     // Create the notification with a title,icon,text,sound and vibration 
     NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context) 
       .setSmallIcon(R.drawable.ic_alarm_white_24dp) 
       .setContentTitle(notificationTitle) 
       .setContentText(notificationText) 
       .setContentIntent(pendingIntent) 
       // Notification auto cancel itself when clicked 
       .setAutoCancel(true) 
       .setSound(uri) 
       .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}) 
       .setLights(Color.BLUE, 3000, 3000); 

     // Build the notification and issue it 
     Notification notification = nBuilder.build(); 
     NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
     nManager.notify(ID, notification); 
    } 
    else { 
     Toast.makeText(context,"null event",Toast.LENGTH_SHORT); 
    } 
} 

}

В верхней части уведомления толкателя пытается получить идентификатор из Extras, но каждый раз, когда приложение удаляется из памяти, он получает по умолчанию значение (-1). Я не знаю, как передать этот идентификатор.

ответ

0

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

https://developer.android.com/guide/components/services.html#Foreground

+0

Так что мне нужно изменить мой IntentService в нормальное обслуживание? Я уже пробовал это, но как я могу добавить дополнительные услуги в службу, если это не намерение? Редактировать: Есть ли другой метод, который не требует постоянного системного уведомления? –

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