xamarin android 如何创建一个服务

//规定红字处一定要小写
以下这个放在Properties/AdnroidManifest.xml文件中
<service android:name=" intelligenceLamp.WebSocketService" android:enabled="true" android:process=":remote">
</service>


以下这个自己创建一个.cs文件即可
创建的服务:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace IntelligenceLamp
{
[Service]
class WebSocketService : Service
{
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
public override void OnCreate()
{
base.OnCreate();
Console.WriteLine("服务被创建");
}

[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Console.WriteLine("服务被启动");
return base.OnStartCommand(intent, flags, startId);
}
public override void OnDestroy()
{
Console.WriteLine("服务被关闭");
base.OnDestroy();
}
}
}

放在MainActivity.cs 的oncreat函数中就可以了(即初始化函数)
开启服务:
StartService(new Intent(this, typeof(WebSocketService)));
发布了28 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_28738419/article/details/77335095