4

I'm trying to have Notification very time the Job service run. It's not working. I want to know the right way of providing notification when the Job service is enabled. Please help me in understanding these concepts and how to make it work? Note: Scheduling is working, I'm trying to add Notification, which is not working.

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() {  
    ......
}

}

Anitha B S
  • 101
  • 1
  • 8

4 Answers4

1

Job scheduling is basically to run long task in background. You should add the notification in FirebaseMessagingService and then start the job to do task in background after adding notification.

Arslan Maqbool
  • 519
  • 1
  • 7
  • 21
1

Yes, I’ve implemented the listener which is scheduled to check for a event. If that meets my requirement then I just call the given below function.

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

Bahman Thanks for asking, Here is our NotificationUtil class:

public class NotificationUtil {
public static String createNotificationChannel(
        Context context) {

    // NotificationChannels are required for Notifications on O (API 26) and above.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        // The id of the channel.
        String channelId = "YOUR_CHANNEL_ID";

        // The user-visible name of the channel.
        CharSequence channelName = "YOUR_CHANNEL_NAME";
        // The user-visible description of the channel.
        String channelDescription = "YOUR_CHANNEL_DESCRIPTION";
        int channelImportance = NotificationManager.IMPORTANCE_HIGH;
        int channelLockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC;

        // Initializes NotificationChannel.
        NotificationChannel notificationChannel = null;
        notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);

        notificationChannel.setDescription(channelDescription);
        notificationChannel.enableVibration(true);
        notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

        // Adds NotificationChannel to system. Attempting to create an existing notification
        // channel with its original values performs no operation, so it's safe to perform the
        // below sequence.
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);

        return channelId;
    } else {
        // Returns null for pre-O (26) devices.
        return null;
    }
}

}

Naveen Kumawat
  • 467
  • 5
  • 12
0

I think there are some potential problems

  • Forgot to add GuardianJobService in AndroidManifest.xml
  • Never meet the condition to run the job (could you show your schedule code?)
  • If you run on device with Android >= 8.0, you need to create Notification Channel in order to receive notification (refer here)
h0102
  • 236
  • 3
  • 11
  • Scheduling is working fine, But Notification is not working – Anitha B S May 02 '18 at 17:17
  • I tried your notification code and it works fine in my device (Android 6). If you are using Android >= 8.0. You should create notification channel. Else, could you try to use some random notification id instead of zero "manager.notify(random_notification_id_here, builder.build());" – h0102 May 14 '18 at 02:16
0

Please create a Notification Channel and register it with your Notification Manager. Use the same notification channel when building a notification. If you are running your code on a device with Android version greater than or equal to Oreo, the app won't trigger a notification, hence you need to have a notification channel for versions Oreo and greater. Refer: https://developer.android.com/training/notify-user/build-notification