Why Start the Service on Android O and encounter a problem record Context.startForegroundService did not then call Service.startForeground

Ponglang Petrung
PongPloyDev
Published in
4 min readAug 10, 2018

Recording scenarios: Android 8.0 has a complex feature; the system does not allow background applications to create background services. Therefore, Android 8.0 introduces a completely new method, Context.startForegroundService(), to start a new service in the foreground.
After the system creates the service, the app has 5 seconds to call the service’s startForeground() method to display the user-visible notification for the new service. If the app does not call startForeground() within this time limit, the system will stop the service and declare the application as ANR.

However, when calling: context.startForegroundService(intent), the following ANR is reported. The startForegroundService() document indicates that startForeground() is called after the service is started.

Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

NotificationCompat.Builder notificationBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, TAG, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableVibration(true);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(notificationChannel);
} else {
notificationBuilder = new NotificationCompat.Builder(this);
}
notificationBuilder
// .setContentTitle(notification.getTitle())
.setContentText(String.format("R.string.workfield_driver_refuse"))
// .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setLargeIcon(icon)
.setColor(Color.RED)
.setSmallIcon(R.mipmap.ic_launcher);

notificationBuilder.setDefaults(DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.YELLOW, 1000, 300);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()

and run App see Error Log

Solution: After starting the service with startForegroundService, call startForeground() in the service’s onCreate method.

private static final String CHANNEL_ID = "1250012";
private static final String TAG = MyNotificationExtenderService.class.getSimpleName();
Class ..... Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

NotificationCompat.Builder notificationBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, TAG, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableVibration(true);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(notificationChannel);
} else {
notificationBuilder = new NotificationCompat.Builder(this);
}
notificationBuilder
// .setContentTitle(notification.getTitle())
.setContentText(String.format("R.string.workfield_driver_refuse"))
// .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setLargeIcon(icon)
.setColor(Color.RED)
.setSmallIcon(R.mipmap.ic_launcher);

notificationBuilder.setDefaults(DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.YELLOW, 1000, 300);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,TAG,
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);

Notification notification = new Notification.Builder(getApplicationContext(),CHANNEL_ID).build();
startForeground(1, notification);
}
else {

// startForeground(1, notification);
}

and try ran again

Note that Notification.Builder(Context, String) is used in api 26, and the Id of NotificationChannel is to be specified. If not added, it will prompt: Developer warning for package XXX, Failed to post notification on channel “null”.

Of course, the configuration of NotificationChannel can refer to: https://developer.android.google.cn/reference/android/app/NotificationChannel.html
Notification.Builder Reference: https://developer.android.google.cn/reference/android/ App/Notification.Builder.html

Front desk service test app address: https://github.com/lyldding/foregroundservice

Credits : https://blog.csdn.net/lylddingHFFW/article/details/78219327

You have followed the group:

https://android-arsenal.com

http://www.tellmehow.co/

ใครสนใจ มา join line ได้ครับ รับจำนวนจำกัด ใครปัญหา ชอบแชร์ มีเรื่องอะไรใหม่ๆ สามารถ join เข้าได้เลยครับ 😁

หากสนใจ ก็สามารถ join ได้ที่นี้เลยครับ . หรือ scan qrcode . ไปได้เลย

[Android Github Dev] คุณได้รับคำเชิญให้เข้าร่วมสแควร์ของ LINE
https://line.me/ti/g2/UVVDK6Z5EE
Android Developer

Thank you for joining: https://www.facebook.com/groups/883546485084033/?fref=ts I created a group of Android Developers Android and Kotlin Droidcon Github library. If you have any questions, you can ask. You can join in the App Telegram. https://t.me/joinchat/IhB5KQ0aXC7ckNgjRaBaCw Now join Android Developers And Kotlin Droidcon Github Library Community Telegram App to help each other. Joining Link:

เข้าร่วม Group Line: เข้าร่วมกลุ่ม

: กล่องจดหมายเพื่อส่งอีเมล pongku71@gmail.com

Android Open Source Projects [inclusion] [SUM] [Join user groups] There is a problem with Android projects and want to give answers. What's new or want to update the robot continuously. Can join. Line: po56789 or inbox on the page, come to join, please just !!!!
Thank you

แฟนเพจ PongPloy Zone AppDev

Link : https://www.facebook.com/PPAndroid-Github-Dev-Zone-170227463027435/notifications/

Language learning application APP .

EN

Practice writing, reading, Kai-ABC, this application. Designed to be easy to use, uncomplicated, with illustrations and sound for train children to read according to Thai-English consonants clearly.Practice writing all 44 Thai consonants from chicken to hawk and 26 English consonants since A-Z makes it easy to learn and remember.This application is suitable for Thai students. And foreigners studying Thai languageAnd in the future, may add more games to children

Thai :

ฝึกเขียน อ่าน ก ไก่-ABC แอพพลิเคชั่นนี้ ออกแบบมาให้ใช้งานง่าย ไม่ซับซ้อน โดยมีภาพประกอบพร้อมเสียงสำหรับฝึก ให้เด็กๆ ท่องตาม อ่านเสียงพยัญชนะ ไทย — อังกฤษ ได้ชัดเจน ฝึกเขียนพยัญชนะไทยทั้ง 44 ตัว ตั้งแต่ ก ไก่ จนถึง ฮ นกฮูก และ พยัญชนะภาษาอังกฤษทั้ง 26 ตัว ตั้งแต่ A-Z ทำให้ง่ายต่อการเรียนรู้และจดจำแอพพลิเคชั่นนี้เหมาะสำหรับเด็กนักเรียนไทย และชาวต่างชาติที่ศึกษาภาษาไทยและต่อไปในอนาคต อาจจะเพิ่ม เกม ให้เด็กมาสนใจมากขึ้น

Download : App link : https://play.google.com/store/apps/details?id=com.pongploydev.education.mediaapp

--

--