2

I'm using the following code:

private void startForeground(boolean isActive) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(getString(isActive ? R.string.title_agent_active : R.string.title_agent_inactive))
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);
    }

and

 @Override
    protected void onHandleIntent(Intent intent) {
        startForeground(true);
        ...

With this code notification does not appear.

But if I replace startForeground(...) with NotificationManager.notify(...) — it shows the notification, so, I think, that at least notification building code is ok.

Where could be the problem?

artem
  • 16,382
  • 34
  • 113
  • 189

2 Answers2

5

If you're using an IntentService the service will be destroyed as soon as onHandleIntent() method finishes execution and then, the notification will be removed.

kleinsenberg
  • 1,323
  • 11
  • 15
1
  1. try to change the id into the other
  2. start in onCreate() method
  3. check the notifications are not blocked in the device
  4. try to use these flags: noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
  5. Use usual Service class

try this solution (works in my app):

private void fg() {
        Intent intent = launchIntent(this);

        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.app_name))
            .setSmallIcon(R.drawable.icon)
            .setContentIntent(pIntent);
        noti = mBuilder.build();
        noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
        startForeground(_.ID, noti);

    }
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194