How to create android notification to keep foreground service alive?

Hi community,

I have been trying to implement a foreground service for android using native code. I have no issue with creating the service itself, but I need to create a notification to inform the user, otherwise the system kills the service after 5 seconds.

I tried this code to create the notification:

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

But it causes the following error. Apparently Unity cannot find the NotificationCompat class.

06-27 11:30:59.643  9748  9777 E Unity   : AndroidJavaException: java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/core/app/NotificationCompat$Builder;
06-27 11:30:59.643  9748  9777 E Unity   : java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/core/app/NotificationCompat$Builder;

Does anybody know an example of how to start a foreground service in android from unity? Or a recent example of how to implement notifications? Most examples on the internet are too old and don’t work for android version of API 26 (Oreo) or above.

Regards,
David

Hi,

yes. Actually I hired a freelancer on fiverr to do it for me. The Plugin he made didn’t work properly but it helped me to spot the errors I made. It was worth the money afer I spent more than a week without any luck.

Mostly these were errors in the gradle files and unity setup.

Here the link to the fiverr page of that guy: https://www.fiverr.com/koradiyaabhay/develop-android-native-plugin-for-unity?source=order_page_summary_gig_link_title&funnel=9ea84578-4cc3-4263-96fe-fc8e23bc7f8e

Did you have any luck creating a Foreground Service plugin?