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