@DS2107

Как спрятать службу, точнее запустить ее на фоне, но что бы пользователь ее не видел в шторке уведомлений?

У меня есть приложение , подобие популярных мессенджеров (Вк, Telegram) и т.п. Я создал службу которая запускается при старте приложения или при загрузке телефона , это служба слушает входящие сообщения , звонки и другое . Благодаря ей мне приходит уведомления. Но есть одна неприятная проблема , в шторке уведомления остался значок службы , убрать его можно только в настройках телефона и служба будет работать дальше, как и работала. Но мне надо убрать ее программно.
Вот код моего значка который отображается при запуске службы.

using Android.App;
using Android.Content;
using Android.OS;
using AndroidX.Core.App;
using Corporate_messenger.Droid.NotificationManager;

[assembly: Xamarin.Forms.Dependency(typeof(NotificationHelper))]
namespace Corporate_messenger.Droid.NotificationManager
{
    class NotificationHelper : IStaticNotification
    {
        private static string foregroundChannelId = "9003";
        private static Context context = global::Android.App.Application.Context;


        public Notification ReturnNotif()
        {
            // Building intent
            var intent = new Intent(context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.FromBackground);
           // intent.PutExtra("Title", "Message");

            var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent);

            var notifBuilder = new NotificationCompat.Builder(context, foregroundChannelId)
                .SetContentTitle("")
                .SetContentText("")
                .SetSmallIcon(Resource.Drawable.MyChat)
                .SetOngoing(true)
                .SetContentIntent(pendingIntent);

            // Building channel if API verion is 26 or above
            if (global::Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                NotificationChannel notificationChannel = new NotificationChannel(foregroundChannelId, "Title", NotificationImportance.High);
                notificationChannel.Importance = NotificationImportance.High;
                notificationChannel.EnableLights(true);
                notificationChannel.EnableVibration(true);
                notificationChannel.SetShowBadge(true);
                notificationChannel.SetVibrationPattern(new long[] { 0L });

                var notifManager = context.GetSystemService(Context.NotificationService) as Android.App.NotificationManager;
                if (notifManager != null)
                {
                    notifBuilder.SetChannelId(foregroundChannelId);
                    notifManager.CreateNotificationChannel(notificationChannel);
                }
            }

            return notifBuilder.Build();
        }
    }
}


Вот код запуска службы:
using Android.App;
using Android.Content;
using Android.OS;
using Corporate_messenger.Droid.NotificationManager;
using Corporate_messenger.Models;
using Corporate_messenger.Models.Chat;
using Corporate_messenger.Service;
using Corporate_messenger.Service.Notification;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.ComponentModel;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(startServiceAndroid))]
public class startServiceAndroid : IForegroundService
    {
       
        private static Context context = global::Android.App.Application.Context;

        public bool AudioCalls_Init { get; set; }

        public void StartService()
        {
             var intent = new Intent(context, typeof(NotoficationService));
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                context.StartForegroundService(intent);
            }
            else
            {
                context.StartService(intent);
            }
        }

        public void StopService()
        {
            var intent = new Intent(context, typeof(NotoficationService));
            context.StopService(intent);
        }
    }

Вот фото
61c0447ab61f4870399957.png
  • Вопрос задан
  • 155 просмотров
Пригласить эксперта
Ответы на вопрос 1
402d
@402d
начинал с бейсика на УКНЦ в 1988
поведение от которого вы хотите избавиться - заложено в самой операционной системе.
Никак.
https://developer.android.com/guide/components/for...
Без видимого нотифи оптимизация батареи прибивает службу сразу.
5 секунд и если нет уведомления - отвал
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы