Могу ли я отправить уведомление с помощью планировщика заданий? - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь получить Уведомление во время работы службы заданий. Это не работает. Я хочу знать правильный способ предоставления уведомлений, когда служба Job включена. Пожалуйста, помогите мне понять эти понятия и как заставить это работать? Примечание : планирование работает, я пытаюсь добавить уведомление, которое не работает.

public class GuardianJobService  extends JobService{
     public final int REQUEST_CODE_ASK_PERMISSIONS = 1001;
@Override
public boolean onStartJob(JobParameters params) {
    enableTracking();
    addNotification();
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    return true;
}

private void addNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.alert_icon)
                    .setContentTitle("Notifications Example")
                    .setContentText("This is a test notification");
    Intent notificationIntent = new Intent(this, LoginActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0, builder.build());
}
public void enableTracking() {  
    ......
}

}

Ответы [ 4 ]

0 голосов
/ 21 апреля 2019

Пожалуйста, создайте канал уведомлений и зарегистрируйте его в вашем менеджере уведомлений. Используйте тот же канал уведомлений при создании уведомления. Если вы выполняете свой код на устройстве с версией Android, большей или равной Oreo, приложение не будет вызывать уведомление, поэтому вам необходим канал уведомлений для версий Oreo и выше. См .: https://developer.android.com/training/notify-user/build-notification

0 голосов
/ 02 мая 2018

Планирование заданий в основном для запуска длинной задачи в фоновом режиме. Вы должны добавить уведомление в FirebaseMessagingService и затем запустить задание для выполнения задачи в фоновом режиме после добавления уведомления.

0 голосов
/ 12 марта 2019

Да, вы можете, но только локальное уведомление (не на базе Firebase или на сервере), и я понимаю, что если вы зададите этот вопрос, это будет вашим единственным требованием.

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

private void generateBigTextStyleNotification() {
    String notificationChannelId =
            NotificationUtil.createNotificationChannel(thisService);

    String title = "Your title";
    String msg = "Your message";

    NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
            .bigText(msg)
            .setBigContentTitle(title)
            .setSummaryText("Your Summary");

    PendingIntent notifyPendingIntent =
            PendingIntent.getActivity(
                    thisService,
                    0,
                    new Intent(),
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    //Build and issue the notification.

    // Notification Channel Id is ignored for Android pre O (26).
    NotificationCompat.Builder notificationCompatBuilder =
            new NotificationCompat.Builder(
                    thisService, notificationChannelId);
    notificationCompatBuilder.setAutoCancel(true);
    GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);
    Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + thisService.getPackageName() + "YourSoundPath");
    Notification notification = notificationCompatBuilder
            // BIG_TEXT_STYLE sets title and content for API 16 (4.1 and after).
            .setStyle(bigTextStyle)
            // Title for API <16 (4.0 and below) devices.
            .setContentTitle(title)
            // Content for API <24 (7.0 and below) devices.
            .setContentText(msg)
            .setSmallIcon(R.drawable.ic_launcher)
            .setSound(alarmSound)
            .setLargeIcon(BitmapFactory.decodeResource(
                    thisService.getResources(),
                    R.mipmap.ic_launcher))
            .setContentIntent(notifyPendingIntent)
            .setDefaults(NotificationCompat.FLAG_AUTO_CANCEL)
            // Set primary color (important for Wear 2.0 Notifications).
            .setColor(ContextCompat.getColor(thisService, R.color.secondary_background_color))
            .setCategory(Notification.CATEGORY_EVENT)

            // Sets priority for 25 and below. For 26 and above, 'priority' is deprecated for
            // 'importance' which is set in the NotificationChannel. The integers representing
            // 'priority' are different from 'importance', so make sure you don't mix them.
            .setPriority(NotificationCompat.PRIORITY_MAX)

            // Sets lock-screen visibility for 25 and below. For 26 and above, lock screen
            // visibility is set in the NotificationChannel.
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setAutoCancel(true)

            // Adds additional actions specified above.
            .build();
    mNotificationManagerCompat.notify(NOTIFICATION_ID, notification);
}
0 голосов
/ 02 мая 2018

Я думаю, что есть некоторые потенциальные проблемы

  • Забыл добавить GuardianJobService в AndroidManifest.xml
  • Никогда не выполняйте условие для запуска задания (не могли бы вы показать код расписания?)
  • Если вы работаете на устройстве с Android> = 8.0, вам нужно создать канал уведомлений, чтобы получать уведомления (см. здесь )
...