4

I have this service that will connect to the server and fetch notifications but unfortunately it doesn't show any notification this is the service class :

public class NotificationService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void startNotificationListener()
    {
      //start's a new thread
    new Thread(new Runnable() {
        @Override
        public void run() {
          //fetching notifications from server
         //if there is notifications then call this method
        ShowNotification();
        }
    }).start();
    @Override
    public void onCreate()
    {
        startNotificationListener();
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent,int flags,int startId)
    {
        return super.onStartCommand(intent,flags,startId);
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }
    public void ShowNotification()
    {
      NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
            Notification notification = new NotificationCompat.Builder(getBaseContext(),"notification_id")
                    .setSmallIcon(R.drawable.icon)
                    .setContentTitle("title")
                    .setContentText("content")
                    .setDefaults(NotificationCompat.DEFAULT_SOUND)
                    .build();
            notificationManager.notify(0, notification);
       //the notification is not showing

    }
}

and the notification is not showing when calling ShowNotification, I've tried pasting ShowNotification's code inside the main activity's oncreate like that

@Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
          NotificationManager notificationManager =
                (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(getBaseContext(),"n")
                .setSmallIcon(R.drawable.icon)
                .setContentTitle("Title")
                .setContentText("Content Text"))
                .setDefaults(NotificationCompat.DEFAULT_SOUND)
                .build();
        notificationManager.notify(0, notification);
    }

and it works.

Do I always need to create a notification from an activity ? if not, how to create a notification from a service ?

P.S: the service will run even if the app is not running

mr.infin8
  • 53
  • 1
  • 1
  • 5
  • You never call `startNotificationService()` in `NotificationService` anywhere. You do call `startNotificationListener()`, but that method doesn't seem to exist. – Mike M. Feb 27 '18 at 02:03
  • I'm sorry it's a mistake the methode is StartNotificationListener – mr.infin8 Feb 27 '18 at 02:04
  • edited the question.. – mr.infin8 Feb 27 '18 at 02:05
  • Please edit again to include a [mcve]. The current edit still will not compile; e.g., there is no `args` declared anywhere. – Mike M. Feb 27 '18 at 02:14
  • Args are just arguments passed from the fetching process they contain notification information you can try it without args , the problem is the notification does not show no matter how i use it inside the service – mr.infin8 Feb 27 '18 at 02:15
  • anyway i've removed them from the question – mr.infin8 Feb 27 '18 at 02:17
  • Which Android version are you testing on? If Oreo, are you sure the channel has been created first? Otherwise, are you certain the `Service` is even running? If it is, have you debugged to make sure that `args` is actually valid, and returning non-null values? Have you been checking your logcat for any possible errors? – Mike M. Feb 27 '18 at 02:26
  • Its Kitkat, the service is running and i can communicate with it from the app the args are fine everything is fine the only problem is the notification is not showed on the drawer – mr.infin8 Feb 27 '18 at 02:28
  • Have you tried to do it from IntentService instead of Service? – Anton Makov Feb 27 '18 at 02:40
  • No i didn't I will try it tomorrow and let you know – mr.infin8 Feb 27 '18 at 02:46

3 Answers3

2

Yes you can create notification from service.but as per your code the close bracket of startNotificationListener() is missing after below code

new Thread(new Runnable() { @Override public void run() { //fetching notifications from server //if there is notifications then call this method ShowNotification(); } }).start();

and you have to register service in AndroidManifest.Xml file before </application>.

<service android:name=".NotificationService"/>

after that, you have to start service from your activity as per below.

startService(new Intent(this,NotificationService.class));

there is the code of your service:

public class NotificationService extends Service {

public void startNotificationListener() {
    //start's a new thread
    new Thread(new Runnable() {
        @Override
        public void run() {
            //fetching notifications from server
            //if there is notifications then call this method
            ShowNotification();
        }
    }).start();
}
@Override
public void onCreate()
{
    startNotificationListener();
    super.onCreate();
}
@Override
public int onStartCommand(Intent intent,int flags,int startId)
{
    return super.onStartCommand(intent,flags,startId);
}
@Override
public void onDestroy()
{
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void ShowNotification()
{
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
    Notification notification = new NotificationCompat.Builder(getBaseContext(),"notification_id")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("title")
            .setContentText("content")
            .setDefaults(NotificationCompat.DEFAULT_SOUND)
            .build();
    notificationManager.notify(0, notification);
    //the notification is not showing

}

}

you will get the notification.please check screen shot

enter image description here

Pratik Satani
  • 1,115
  • 1
  • 9
  • 25
  • Hello Patrik, Thanks for your time The Service is working , i made some errors while rewriting the code here but in my project the code is okay, i can tell that because i use Log and it's showing that the service is running but no matter what i do the notification wont show on the Kitkat(The phone i'm using now) i've tried on a simulator (Oreo) it didn't work there too – mr.infin8 Feb 27 '18 at 11:43
0

Try using Notification channels...may be that's the problem.

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear.

https://developer.android.com/guide/topics/ui/notifiers/notifications.html#ManageChannels

        // The id of the channel.
        String CHANNEL_ID = "my_channel_01";
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this).setChannel(CHANNEL_ID)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("My notification")
                        .setContentText("Hello World!");
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, MainActivity.class);

        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your app to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // mNotificationId is a unique integer your app uses to identify the
        // notification. For example, to cancel the notification, you can pass its ID
        // number to NotificationManager.cancel().
        mNotificationManager.notify(0, mBuilder.build());

https://github.com/fida1989/NotificationDemo

fida1989
  • 3,234
  • 1
  • 27
  • 30
  • Hello fida, Thanks for your time but as far as i know the channels arn't necessary on Kitkat, by the way i did use them before and it doesn't work – mr.infin8 Feb 27 '18 at 11:46
0

The problem is not your code or the channel.You need to check that the data you are fetching from the server is being returned and passed inside the setContentTitle() and setContentText() methods of the builder class.

I had the same problem with firebase. Until I realise the data I needed was not being returned. If the app crashes after some time, it's because the service is waiting for null data that is not being returned from the server even if the service started running initially.

Bishan
  • 15,211
  • 52
  • 164
  • 258