创建xamarin进程永不结束

问题描述 投票:1回答:1

我有一个计划,想每5分钟定期检查一次URL(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);
            }
        }
    }
}
xamarin xamarin.forms xamarin.android
1个回答
0
投票

欢迎您来到马吉德!是的,即使原始程序/应用程序不在前台,也可以运行进程。

您正在输入“背景”区域,这不太容易做到。没有使用Xamarin.Forms执行后台内置/正式的方式,因此您将不得不创建依赖项服务(shown here),或尝试使用Shiny

如果遵循依赖性服务路线,则只需遵循iOS和Android官方教程,并在您的Native项目中实现它们。请注意,如果您只需要定期警报,则Android提供了更简单的Alarm / PowerManager可供您使用。

© www.soinside.com 2019 - 2024. All rights reserved.