You can try to use both methods, first start the service with startForeground() and then use bindService() to wait for the service connection.
The service starts in the foreground and you can use the service methods.
Starting Service:
listenServiceIntent = new Intent(getApplicationContext(), ListenService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Start in Foreground
ContextCompat.startForegroundService(this, listenServiceIntent);
if (connection != null) {
//Then bind service
bindService(listenServiceIntent, connection, Context.BIND_AUTO_CREATE);
}
}
else {
startService(listenServiceIntent);
if (connection != null) {
bindService(listenServiceIntent, connection, Context.BIND_AUTO_CREATE);
}
}
Waiting Connection:
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "onServiceConnected");
ListenService.LocalBinder binder = (ListenService.LocalBinder) service;
listenService = binder.getService();
//HERE you can use service methods
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "onServiceDisconnected");
}
};
Create notificationChannel:
public static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
NOTIFICATION_CHANNEL,
NOTIFICATION_NAME,
NotificationManager.IMPORTANCE_HIGH
);
NotificationManager manager = context.getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(serviceChannel);
}
}
}
Push notification:
public static Notification pushNotification(Context context, String notificationText, Class classNotification) {
Intent notificationIntent = new Intent(context, classNotification);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, notificationIntent, 0);
return new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL)
.setContentTitle(context.getString(R.string.notification_title))
.setContentText(notificationText)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.logosinfondo_mini)
.setColor(Color.MAGENTA)
.setAutoCancel(true)
.build();
}
In onCreate() inside your Service:
@Override
public void onCreate() {
super.onCreate();
Lib.createNotificationChannel(this);
startForeground(1, Lib.pushNotification(this, "Started", ListenActivity.class));
}