создать процесс xamarin никогда не закончится - PullRequest
1 голос
/ 26 января 2020

У меня есть план, и я хочу периодически проверять URL каждые 5 минут (NOTIFY CENTER SERVER (Listener)).

Моя проблема: после закрытия программы процесс закрывается Возможно ли, что проект будет не выключаться, если исходная программа закрыта?

Мой код после изменения Работал с: Matcha.BackgroundService

using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Matcha.BackgroundService.Droid;
using Matcha.BackgroundService;
using System.Threading.Tasks;
using Android.Util;
using System.Threading;
using AndroidApp = Android.App.Application;
using Android.Content;
using Android.Support.V4.App;
using Android.Graphics;

namespace Solution.Droid
{
    [Activity(Label = "Solution", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        private NotificationManager _manager;
        private bool _channelInitialized = false;
        public const int _pendingIntentId = 0;
        public int _channelID = 10001;
        private long _mssageID=0;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            BackgroundAggregator.Init(this);

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }

        protected override void OnStart()
        {
            base.OnStart();
            //Register Periodic Tasks
            var _notifyTASK = new DevinuxTaskPeriodic(10);
            _notifyTASK.DoTask += () =>
            {
                SendNotify("salam", DateTime.Now.ToString());


            };
            BackgroundAggregatorService.Add(() => _notifyTASK);
            BackgroundAggregatorService.StartBackgroundService();
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        public int SendNotify(string title, string message)
        {
            _mssageID++;
            if (!_channelInitialized)
            {
                CreateNotificationChannel();
            }


            Intent intent = new Intent(AndroidApp.Context, typeof(MainActivity));

            PendingIntent pendingIntent = PendingIntent.GetActivity(AndroidApp.Context, _pendingIntentId, intent, PendingIntentFlags.OneShot);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidApp.Context, _channelID.ToString())
                .SetContentIntent(pendingIntent)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetLargeIcon(BitmapFactory.DecodeResource(AndroidApp.Context.Resources, Resource.Drawable.notification_template_icon_bg))
                .SetSmallIcon(Resource.Drawable.notification_template_icon_bg)
                .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate);

            Notification notification = builder.Build();
            _manager.Notify((int)_mssageID, notification);

            return (int)_mssageID;
        }
        void CreateNotificationChannel()
        {
            _manager = (NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelNameJava = new Java.Lang.String("Solution");
                var channel = new NotificationChannel(_channelID.ToString(), channelNameJava, NotificationImportance.Default)
                {
                    Description = "My Company Notify Camp."
                };
                _manager.CreateNotificationChannel(channel);
            }

            _channelInitialized = true;

        }
        public class DevinuxTaskPeriodic : IPeriodicTask
        {
            public bool use { set; get; } = false;
            public delegate void DoArgs();
            public event DoArgs DoTask;
            public DevinuxTaskPeriodic(int seconds)
            {
                Interval = TimeSpan.FromSeconds(seconds);
            }
            public TimeSpan Interval { get; set; }
            public Task<bool> StartJob()
            {
                if (!use)
                {
                    Timer tmr = new Timer((o) => {
                        if (DoTask != null)
                        {
                            DoTask();
                        }
                    }, null, 0, (int)Interval.TotalSeconds*1000);
                }
                use = true;
                return new Task<bool>(() => true);
            }
        }
    }
}

1 Ответ

0 голосов
/ 27 января 2020

Добро пожаловать в Маджид! Да, можно запускать процессы, даже если исходная программа / приложение не находится на переднем плане.

Вы входите на территорию «фонового изображения», что сделать не так просто. Не существует встроенного / официального способа выполнения фоновой обработки с использованием Xamarin.Forms, поэтому вам придется либо создать службу зависимостей ( показано здесь ), либо попробовать использовать Shiny .

Если вы следуете по пути служб зависимостей, вам просто нужно следовать официальным учебным пособиям iOS & Android и внедрять их в свой проект Native. Обратите внимание, что если вам нужен только периодический c сигнал тревоги, Android предоставляет более простой Alarm / PowerManager , который вы можете использовать.

...