My app will call startForegroundService(intent)
in the onCreate
of the MainActivity
. And I put startForeground(ON_SERVICE_CONNEC
I am facing same issue and after spending time found a solutons you can try below code. If your using Service
then put this code in onCreate
else your using Intent Service
then put this code in onHandleIntent
.
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_app";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"MyApp", NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
and call this
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(getSyncIntent(context));
} else {
context.startService(getSyncIntent(context));
}
I experienced this issue for Galaxy Tab A(Android 8.1.0). In my application, I start a foreground service in the constructor of MainApplication
(Application-extended class). With the Debugger, I found it took more than 5 second to reach OnCreate()
of the service after startForegroundService(intent)
. I got crash even though startForeground(ON_SERVICE_CONNECTION_NID, notification)
got called in OnCreate()
.
After trying different approach, I found one works for me as the following:
In the constructor, I used AlarmManager
to wakeup a receiver, and in the receiver, I started the foreground service.
I guessed that the reason I had the issue because heavy workload of application starting delayed the creation of the foreground service.
Try my approach, you might resolve the issue as well. Good luck.
i had the same problem.
What helped me in the end, was to initialize the NotificationChannel as early as possible ( i did it in the application class itself) and then create and use the notification in the service.
I put this in the Application class:
private void createNotificationChannel() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "MyStreamingApplication";
String description = "radio";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setSound(null, null);
mChannel.enableVibration(false);
mChannel.setDescription(description);
notificationManager.createNotificationChannel(mChannel);
}
}
and in the onStartCommand method of the service i call:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
startForeground(NOTIFICATION_ID, createNotification());
}