本文介绍了如何在 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 8.0(API级别26)及以上版本的Android应用不再具备在后台自由运行的能力.当应用程序进入后台时,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 中创建在一段时间内工作的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 22:29