如何在Xamarin.Forms中的时段创建服务工作? [英] How to create service doing work at period time in Xamarin.Forms?

查看:89
本文介绍了如何在Xamarin.Forms中的时段创建服务工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建的应用程序是在应用程序首次运行时运行的,大约1个小时或更长时间之后,即使用户关闭了该应用程序,它仍会自动连接到服务器以获取数据以进行配对显示

I'm building application that is when the application run first time, after that about 1 hours or more, it is automatic connect to server get data for prepair display eventhough the user close the app

推荐答案

首先,当用户关闭应用程序时,后台服务器无法与打开应用程序一样运行,它将被Android系统关闭.

First of all, when user close the app, the background servers cannot running the same as open the app, it will be closed by Android system.

如果应用程序在后端运行,则Android应用程序将无法再在Android 8.0(API级别26)或更高版本中在后台自由运行.当应用程序进入后台时,Android将为该应用程序分配一定的时间来启动和使用服务.该时间过后,该应用将无法再启动任何服务,并且所有已启动的服务都将终止.此时,该应用程序无法执行任何工作.

If app running in the backend, Android application no longer have the ability to run freely in the background in Android 8.0 (API level 26) or above. When an application moves into the background, Android will grant the app a certain amount of time to start and use services. Once that time has elapsed, the app can no longer start any services and any services that were started will be terminated. At this point it is not possible for the app to perform any work.

因此,根据您的需求,在前台启动服务是一个不错的选择(但用户无法关闭此应用程序)–当应用程序必须在其中执行某些任务时,前台服务非常有用背景和用户可能需要定期与该任务进行交互.前台服务将显示持久性通知,以便用户知道该应用程序正在运行后台任务,并且还提供了一种监视任务或与任务交互的方法.

So, based on your needs, Start the service in the foreground is a good choice(but user cannot close this application) – a foreground service is useful for when the app must perform some task in the background and the user may need to periodically interact with that task. The foreground service will display a persistent notification so that the user is aware that the app is running a background task and also provides a way to monitor or interact with the task.

有我的代码.

MainPage.cs

public partial class MainPage : ContentPage
{
   static bool isRunning = true;
    public MainPage()
    {
        InitializeComponent();
        // BindingContext = new CollectionViewModel();


        if(isRunning){
            //setting one hours to open the service.
            Device.StartTimer(TimeSpan.FromHours(1), () =>
            {
                // Do something
                DependencyService.Get<IService>().Start();
                return false; // True = Repeat again, False = Stop the timer
            });
            isRunning = false;
        }

        bt1.Clicked += (o, e) =>
        {

             Navigation.PushAsync(new Page1());
        };
    }

我使用dependencyservice达到了forground service.

I used dependenceservice to achieve to forground service.

IService.cs 为Android创建界面以启动服务.

IService.cs create a interface for android to start service.

public interface IService
{
    void Start();
}

然后达到DependentService来启动前台服务.

Then achieved DependentService to start a Foreground Service.

DependentService.cs

[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
[Service]
public class DependentService : Service, IService
{
    public void Start()
    {
        var intent = new Intent(Android.App.Application.Context, 
 typeof(DependentService));


        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            Android.App.Application.Context.StartForegroundService(intent);
        }
        else
        {
            Android.App.Application.Context.StartService(intent);
        }
    }

    public override IBinder OnBind(Intent intent)
    {
        return null;
    }
    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 = "service starting";

        var notification = new Notification.Builder(this, "10111")
        .SetContentTitle(Resources.GetString(Resource.String.app_name))
        .SetContentText(messageBody)
        .SetSmallIcon(Resource.Drawable.main)
        .SetOngoing(true)
        .Build();
        StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
        //do you work
        return StartCommandResult.Sticky;
    }


    void CreateNotificationChannel()
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            // Notification channels are new in API 26 (and not a part of the
            // support library). There is no need to create a notification
            // channel on older versions of Android.
            return;
        }

        var channelName = Resources.GetString(Resource.String.channel_name);
        var channelDescription = GetString(Resource.String.channel_description);
        var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
        {
            Description = channelDescription
        };

        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }
}
}

有正在运行的屏幕截图.(为得到快速结果,我将时间跨度设置为6秒)

There is running screenshot.(For a quick result, i set the timesspan to 6 secound)

这篇关于如何在Xamarin.Forms中的时段创建服务工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆