I am able to show heads up notifications from the service. It pop up very first notification and visible to user. But thereafter if the notification is updated then it is not popping up again as first one rather it only gives notification sound and updates it, but does not pop up again as very first.
Showing very first notification from service as below :
public class WatchMan extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";
public boolean Notif_Seven = false;
public boolean Notif_Eight = false;
public WatchMan() { }
#Override
public void onCreate()
{
try
{
mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this, null);
mBuilder.setContentTitle("App Title")
.setContentText("Up and Monitoring..")
.setTicker("Up and Monitoring..")
.setSmallIcon(R.drawable.ic_service_success)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.setOnlyAlertOnce(false)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
mNotifyManager.createNotificationChannel(notificationChannel);
}
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotifyManager.notify(1, mBuilder.build());
startForeground(1, mBuilder.build());
}
catch(Exception e)
{
Log.d(TAG, "EXCEPTION IN SHOWING NOTIFICATION...\n");
Log.e(TAG, "Exception is : ", e);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// STICKY Runnable thread WHILE ( TRUE )
// my code goes here with multiple conditions checking
// Say condition 7 is false and want to notify user again.
if (!Notif_Seven)
{
Notif_Seven = true;
mBuilder.setContentText("SET DEFAULT TYPE IN SETTINGS..");
mBuilder.setTicker("SET DEFAULT TYPE IN SETTINGS..");
mNotifyManager.notify(1, mBuilder.build());
}
Thread.sleep(10000);
continue;
// Say condition 8 is false and want to notify user again.
if (!Notif_Eight)
{
Notif_Eight = true;
mBuilder.setContentText("SET PERCENTAGE SETTINGS..");
mBuilder.setTicker("SET PERCENTAGE SETTINGS..");
mNotifyManager.notify(1, mBuilder.build());
}
}
}
It showing multiple notification tickers in 4.1 one by one, But in 5.1 onwards it shows it as heads up notifications, as it should be but only very first is popping up and rest all notifications are getting updated but not popping up. I want to let user see every notification as heads up and completely visible.
Finally i have done it with startforeground call. It is working as heads up notifications above 5.1 and in below versions it is showing ticker notifications successfully.
public class WatchMan extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";
public boolean Notif_Seven = false;
public boolean Notif_Eight = false;
public WatchMan() { }
#Override
public void onCreate()
{
try
{
mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this, null);
mBuilder.setContentTitle("App Title")
.setContentText("Up and Monitoring..")
.setTicker("Up and Monitoring..")
.setSmallIcon(R.drawable.ic_service_success)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.setOngoing(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
mNotifyManager.createNotificationChannel(notificationChannel);
}
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
//mNotifyManager.notify(1, mBuilder.build());
startForeground(1, mBuilder.build());
}
catch(Exception e)
{
Log.d(TAG, "EXCEPTION IN SHOWING NOTIFICATION...\n");
Log.e(TAG, "Exception is : ", e);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// STICKY Runnable thread WHILE ( TRUE )
// my code goes here with multiple conditions checking
// Say condition 7 is false and want to notify user again.
if (!Notif_Seven)
{
Notif_Seven = true;
mBuilder.setContentText("SET DEFAULT TYPE IN SETTINGS..");
mBuilder.setTicker("SET DEFAULT TYPE IN SETTINGS..");
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
startForeground(1, mBuilder.build());
}
Thread.sleep(10000);
continue;
// Say condition 8 is false and want to notify user again.
if (!Notif_Eight)
{
Notif_Eight = true;
mBuilder.setContentText("SET PERCENTAGE SETTINGS..");
mBuilder.setTicker("SET PERCENTAGE SETTINGS..");
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
startForeground(1, mBuilder.build());
}
}
}
Related
Hi guys as the title suggests I have a problem regarding Firebase Cloud Messaging, everything works perfectly even when the device does not open the app for a long time, receives notifications perfectly, but the problem occurs when I schedule the daily notification via the console firebase li the first time of sending works and sends the notification to all devices, while the next day at the scheduled time the notification is no longer received and this problem I do not know how to solve it, I have tried everything without any solution, the daily notifications do not are received, can you help me thanks.
#SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class MyFirebaseMessagingService extends FirebaseMessagingService {
/*public static int NOTIFICATION_ID = 1;*/
public static String NOTIFICATION = "notification";
public static String NOTIFICATION_CHANNEL_ID = "com.fourapper.forpaper.channel";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
generateNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}
private void generateNotification(String body, String title) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
/*PendingIntent pendingIntent = PendingIntent.getActivities(this, 0 , new Intent[]{intent}, PendingIntent.FLAG_ONE_SHOT);*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
/*NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);*/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_logo_forpapaer)
.setVibrate(new long[]{100, 500})
.setSound(soundUri)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("info")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = null;
if (intent.hasExtra(NOTIFICATION)) {
notification = intent.getParcelableExtra(NOTIFICATION);
}
int notificationId = (int) System.currentTimeMillis();
notificationManager.notify(notificationId, notification);
/*if(NOTIFICATION_ID > 2147483646){
NOTIFICATION_ID = 0;
}*/
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Channel");
notificationChannel.setBypassDnd(true);
notificationChannel.enableLights(true);
notificationChannel.setVibrationPattern(new long[]{ 0, 500});
notificationChannel.enableVibration(true);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(notificationId, builder.build());
}
}
below the token
public class GettingDeviceTokenService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
String deviceToken = FirebaseInstanceId.getInstance().getToken();
assert deviceToken != null;
Log.d("Device Token", deviceToken);
}
}
Below are the photos of the firebase cloud messaging console for scheduled daily sending at 12:00 AM Recipient Time Zone
sending setting change screen
I'm trying to send a notification from an IntentService.
I do get all the logs, but I don't get the notification (Using my galaxy s8 instead of an emulator).
I've tried to extend Service and I have tried to use a scheduler, but both did not work.
Service Code:
public class AppService extends IntentService {
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;
public AppService() {
super("AppService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.d("AppService", "Started");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
Log.d("AppService", "Sending notification");
sendNotification("We might have some brand new movies to offer you!");
Log.d("AppService", "Notification sent");
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("AppService", "1");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Analyze.class), 0);
Log.d("AppService", "2");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("MyCienma")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSmallIcon(R.drawable.icon_500x500_no_edge)
.setContentText(msg);
Log.d("AppService", "3");
mBuilder.setContentIntent(contentIntent);
Log.d("AppService", "4");
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d("AppService", "5");
}
}
I do get all the Logs, but I don't get any notification.
My project's min version is 21 and my phone is running 26. Is that a problem?
Yes, just because you have to set the notification channel id after android version 8.0(api 26).
Reference link:here
Hope! this will help you.
Happy coding...
After API v26 you have to define a NotificationChannel for every notification
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
I want to just Generate a notification after save Video.
for this i'll try below code :
public void stopRecordingVideo() {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.MediaColumns.DATA, file.toString());
activity.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(activity, "Video saved: " + file, Toast.LENGTH_SHORT).show();
//Log.v(TAG, "Video saved: " + getVideoFile(context));
Log.v(TAG, "Video saved: " + file);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText("Hello word") // message for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(activity, RecorderActivity.class);
PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
} else{
// do something for phones running an SDK before lollipop
}
try{
mMediaRecorder.stop();
mMediaRecorder.release();
}catch(RuntimeException stopException){
//handle cleanup here
}
try {
mSession.stopRepeating();
} catch (CameraAccessException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setup2Record();
} else {
finish(); //just blows up anyway.
}
}
Video save perfectly in Storage and Toast msg also show. but only notification not generated please help for this solution.
Solution:
On Android 8.0 (Oreo) you must have something called as a NotificationChannel So try the below implementation:
Step1: Create Notification Channel
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Finally: Then your Notification:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText("Hello word") // message for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(activity, RecorderActivity.class);
PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
notificationManager.notify(1, mBuilder.build());
Try this, Hope it helps.
I'm struggling with complex local notifications on Android for a long time now.
I have a list of events. The user is able to choose when he/she would like to be notified:
on the same day of the event
one day before the event starts
two days before the event starts
He/she is also able to set the time when he/she wants to get notified. Every time is possible. He/she is also able to only get notified by different types of events.
What happens is, that it works fine with every device except the Samsung Galaxy Phones. Users told me that they are receiving a notification exactly one time (when they set them up) and then never again.
I tried almost everything, I'm running out of ideas. It looks like Samsung has some issues with notifications but it works for some other apps. So what's the difference between their code and mine.
Maybe someone else knows this issue and can help me out. This would be so amazing!
Here comes my code:
public int setEventNotifications(List<Event> chosenEvents) {
SharedPreferences settings = context.getSharedPreferences(Constants.PREFS_EVENT_SETTINGS, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<>();
// To cancel an existing pending intent you need to recreate the exact same and cancel it -__-
// So pending intents need to be stored in the database
deleteOldGarbagePendingIntents();
// get notification settings from shared prefs
int hours = 0;
int minutes = 0;
String time = settings.getString(Constants.PREFS_EVENT_TIME, "00:00");
String parts[] = time.split(":");
try {
hours = Integer.parseInt(parts[0]);
minutes = Integer.parseInt(parts[1]);
} catch (Exception e) {
Log.e(TAG, "Invalid time. Cannot be parsed: " + time);
}
String interval = settings.getString(Constants.PREFS_EVENT_INTERVAL, "");
String communeId = settings.getString(Constants.PREFS_EVENT_COMMUNE_ID, "");
String regionId = settings.getString(Constants.PREFS_EVENT_REGION_ID, "");
for (Event event : chosenEvents) {
// check if date is in the future
Intent intent = new Intent(context, AlarmGarbageReceiver.class);
intent.putExtra("request_code", Integer.parseInt(event.getId()));
intent.putExtra("event_type", event.getGarbageType().getType());
intent.putExtra("event_date", event.getPickupDateAsDate().getTime());
// calculate trigger time
long triggerTime = calculateTriggerTime(event.getPickupDateAsDate(), hours, minutes, interval);
Calendar alarmCalendar = Calendar.getInstance();
alarmCalendar.setTimeInMillis(triggerTime);
try {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, Integer.parseInt(event.getId()), intent, FLAG_UPDATE_CURRENT);
if (alarmManager != null) {
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pendingIntent);
} else {
Log.e(TAG, "Alarmmanager is null");
}
intentArray.add(pendingIntent);
// save intents in database
dbHelper.insertEventData(event.getId(), event.getEventType().getType(), String.valueOf(event.getPickupDateAsDate().getTime()), event.getLocation(), event.getEventType().getColor(), communeId, regionId);
} catch (SecurityException securityException) {
Log.e(TAG, "Security Exception");
securityException.printStackTrace();
} catch (Exception exception) {
Log.e(TAG, "Exception");
exception.printStackTrace();
}
}
return intentArray.size();
}
AlarmEventReceiver class:
public class AlarmEventReceiver extends BroadcastReceiver {
private static final String NOTIFICATION_CHANNEL_NAME = "xxx_events";
private static final String NOTIFICATION_CHANNEL_ID = "xxx_events_1";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras() != null) {
Log.e(TAG, AlarmEventReceiver.class.getSimpleName() + " request code: " + intent.getExtras().getInt("request_code"));
}
int eventId = intent.getExtras().getInt("request_code");
String eventType = intent.getExtras().getString("event_type");
long pickupDate = intent.getExtras().getLong("event_date");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(pickupDate);
calendar.set(Calendar.HOUR, 6);
calendar.set(Calendar.MINUTE, 0);
long finalDate = calendar.getTimeInMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder;
Intent resultIntent = new Intent(context, EventCalendarActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(EventCalendarActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
if (notificationManager == null) {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
} else {
Log.e(TAG, "Notification Manager is NULL");
}
if (eventType != null) {
builder.setChannelId(NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle("Erinnerung")
.setContentText(eventType)
.setWhen(finalDate)
.setContentIntent(resultPendingIntent)
.setAutoCancel(false)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
} else {
builder = new NotificationCompat.Builder(context);
builder.setContentTitle("Erinnerung")
.setDefaults(Notification.DEFAULT_ALL)
.setContentText(eventType)
.setWhen(finalDate)
.setContentIntent(resultPendingIntent)
.setAutoCancel(false)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_DEFAULT);
}
Notification notification = builder.build();
if (notificationManager != null) {
notificationManager.notify(eventId, notification);
} else {
Log.e(TAG, "notificationManager is NULL");
}
}
}
I once had the chance to run it on a samsung phone and I think I remember there was some kind of SecurityException thrown because the phone was not able to update notifications. There was only a capacity of 500 notifications and if try to update them, old ones won't be deleted, but new ones created. You therefore reach 500 notifications quite fast and that's when the SecurityException is thrown. But I can't find the source for this anymore...
I browsed a related issue in the past, it happened on a Galaxy Note, although I'm not sure it will help.
mNotificationManager.cancel(notificationId);
mNotificationManager.notify(++notificationId, notification);
Each time a new notification has to be created, manually cancel the previous one and also update the notificationID each time.
It is working fine, tested on Samsung Galaxy s7 edge
fun showDownloadNotification() {
try {
// val selectedUri = Uri.parse(Environment.getExternalStorageState())
val notiIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
notiIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// startActivity(intent);
val pendingIntent: PendingIntent = PendingIntent.getActivity(baseActivity, 0, notiIntent, PendingIntent.FLAG_CANCEL_CURRENT)
val builder = NotificationCompat.Builder(baseActivity, "")
.setSmallIcon(notificationIcon)
.setContentTitle("Subject Topic downloaded")
.setContentText(fileName)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(baseActivity)
// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build())
} catch (e: Exception) {
// Log.e(FragmentActivity.TAG, "Notification $e")
}
}
Might be helpful !
I also had the similar issue with Samsung devices, This is what I have done:
consider this:
builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
In the above line we have passed NOTIFICATION_CHANNEL_ID.
Now later in the code this is also added:
builder.setChannelId(NOTIFICATION_CHANNEL_ID) // don't call this method
We have already given the channel id to the builder via constructor we don't need to pass that again. remove builder.setChannelId(NOTIFICATION_CHANNEL_ID). And it will also work on samsung devices.
To schedule notification:
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class) // the JobService that will be called
.setTag("my-unique-tag") // uniquely identifies the job
.setTrigger(Trigger.executionWindow(0, 5))
.build();
dispatcher.mustSchedule(myJob);
Job service:
public class MyJobService extends JobService
{
#Override
public boolean onStartJob(JobParameters job)
{
// Do some work here
sendNotification("TEST");
return true; // Answers the question: "Is there still work going on?"
}
#Override
public boolean onStopJob(JobParameters job)
{
return false; // Answers the question: "Should this job be retried?"
}
private void sendNotification(String messageBody)
{
Log.d("TEST","Notification: " + messageBody);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Job executed")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Jobs are executing as should (I can see "TEST" in logcat). However, notifications don't appear (without any error thrown).
Do you have any idea why notification not fires? Am I doing something wrong?
Set return false in onStartJob method
public class MyJobService extends JobService {
#Override
public boolean onStartJob(JobParameters job)
{
// Do some work here
sendNotification("TEST");
return false; // Answers the question: "Is there still work going on?"
}...}