Foreground Service in Android 7.0 and Android 5.1.1

Vuyiswa Maseko 351 Reputation points
2021-12-11T23:42:33.16+00:00

Good Day

I have a Foreground Service that works very well , but i have noted some Appcentre Crashes Android 7.0 and Android 5.1.1 , the erro r is

startServiceAndroid.OnStartCommand (Android.Content.Intent intent, Android.App.StartCommandFlags flags, System.Int32 startId)
Java.Lang.NoSuchMethodError: no non-static method "Landroid/app/Notification$Builder;.<init>(Landroid/content/Context;Ljava/lang/String;)V"

InnerException

Xamarin Exception Stack:
Java.Lang.NoSuchMethodError: no non-static method "Landroid/app/Notification$Builder;.<init>(Landroid/content/Context;Ljava/lang/String;)V"
at Java.Interop.JniEnvironment+InstanceMethods.GetMethodID (Java.Interop.JniObjectReference type, System.String name, System.String signature) [0x0005b] in <00c315a988634383b446eff646084784>:0
at Java.Interop.JniType.GetConstructor (System.String signature) [0x0000c] in <00c315a988634383b446eff646084784>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.GetConstructor (System.String signature) [0x00035] in <00c315a988634383b446eff646084784>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.FinishCreateInstance (System.String constructorSignature, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00036] in <00c315a988634383b446eff646084784>:0
at Android.App.Notification+Builder..ctor (Android.Content.Context context, System.String channelId) [0x00094] in <31d0ff079d2b4470befd40c15e1fed76>:0
at Trova.Droid.startServiceAndroid.OnStartCommand (Android.Content.Intent intent, Android.App.StartCommandFlags flags, System.Int32 startId) [0x0000c] in <e78f2bbcd4944d66a44ee50e55b29406>:0
at Android.App.Service.n_OnStartCommand_Landroid_content_Intent_II (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_intent, System.Int32 native_flags, System.Int32 startId) [0x0000f] in <31d0ff079d2b4470befd40c15e1fed76>:0
at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.68(intptr,intptr,intptr,int,int)
at java.lang.NoSuchMethodError: no non-static method "Landroid/app/Notification$Builder;.<init>(Landroid/content/Context;Ljava/lang/String;)V"
at crc64bb2f12474fe6f386.startServiceAndroid.n_onStartCommand(Native Method)
at crc64bb2f12474fe6f386.startServiceAndroid.onStartCommand(startServiceAndroid.java:47)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3394)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1632)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)

Thread 797:
0 java.lang.Object.wait(Object.java:-2)
1 java.lang.Daemons$ReferenceQueueDaemon.run(Daemons.java:150)
2 java.lang.Thread.run(Thread.java:761)

and the code to Start the Service is

NotificationCenter.CreateNotificationChannel();

        Intent intentservice = new Intent(this, typeof(startServiceAndroid));

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            ContextCompat.StartForegroundService(this, intentservice);

        }
        else
        {

            StartService(intentservice);
        }

and the Service Class

[Service]
    class startServiceAndroid : Service, IStartService
    { 
        public void StartForegroundServiceCompat()
        {
            var intent = new Intent(this, typeof(startServiceAndroid));

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                this.Application.ApplicationContext.StartForegroundService(intent);

            }
            else
            {
                this.Application.ApplicationContext.StartService(intent);
            }
        }

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        public override void OnCreate()
        {
            base.OnCreate();
        }

        public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            // From shared code or in your PCL
            CreateNotificationChannel();
            string messageBody = "Push Notification Service";
            var notification = new Notification.Builder(this, "10111")
            .SetContentTitle("My app")
            .SetContentText(messageBody)
           .SetSmallIcon(Resource.Drawable.onesignal)
            .SetOngoing(true)
            .Build();
            StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
            //do you work
            new BackgroundStartup();

            return StartCommandResult.Sticky;
        }
        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            { 
                var channelName = "My app";  
                var channelDescription = "Push Notification for my app "; 
                var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
                {
                    Description = channelDescription
                };
                var notificationManager = (NotificationManager)GetSystemService(NotificationService);
                notificationManager.CreateNotificationChannel(channel);

            }
            else
            {
                return;
            }

        }

Thanks

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,971 Reputation points
    2021-12-13T06:26:09.637+00:00

    Hello @Vuyiswa Maseko ,​

    Welcome to our Microsoft Q&A platform!

    Java.Lang.NoSuchMethodError: no non-static method "Landroid/app/Notification$Builder;

    The Notification.Builder command is deprecated in Api 23, try using the NotificationCompat.Builder method instead. And since Android 8.0, sending a notification needs the NotificationChannel.

    Here is the sample code, you could refer to it.

       private void DispatchNotificationThatAlarmIsGenerated(string message)  
       {  
           var intent = new Intent(this, typeof(MainActivity));  
           ...  
         
           var notificationManager = (NotificationManager)GetSystemService(NotificationService);  
         
           if (Build.VERSION.SdkInt > BuildVersionCodes.O)  
           {  
               NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channelId")  
               .SetContentTitle("Alarm")  
               .SetContentText(message)  
               .SetSmallIcon(Resource.Drawable.abc)  
               .SetAutoCancel(true);  
         
               var chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, GetString(Resource.String.abc_action_bar_home_description), NotificationImportance.Default);  
               chan.LightColor = Android.Graphics.Color.Green;  
               chan.LockscreenVisibility = NotificationVisibility.Private;  
         
               notificationManager.CreateNotificationChannel(chan);  
               notificationManager.Notify(NOTIFICATION_AlARM_ID, notificationBuilder.Build());  
           }  
           else  
           {  
               NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)  
                  .SetDefaults((int)NotificationDefaults.All)  
                  .SetSmallIcon(Resource.Drawable.abc)  
                  .SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })  
                  .SetSound(null)  
                  .SetPriority(NotificationCompat.PriorityDefault)  
                  .SetAutoCancel(false)  
                  .SetContentTitle("Mobile")  
                  .SetContentText("My service started")  
                  .SetOngoing(true);  
         
               notificationManager.Notify(NOTIFICATION_ID, notificationBuilder.Build());  
           }  
       }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.