我正在努力找出在启动应用程序关闭后如何保持Android服务的运行。我试过查看后台服务的示例(例如这 one,以及Xamarin站点上的一些),但是在任何情况下,如果最小化的应用程序在屏幕上被“滑动”,该服务就会停止运行。我不希望服务像这样意外地停止,它应该持续运行,直到请求确认停止为止。该服务不会消耗太多的资源,只需获取GPS位置并每2分钟发布一次到网站。
作为背景,我是Xamarin/Android的新手,但在过去,我用C#在Windows中创建了几个成功的服务
(,后来的)我试过的一个示例确实在运行应用程序的设置列表中留下了一个项目,但一旦从屏幕上删除,实际上并没有执行任何服务任务。此外,状态栏中没有图标。经过一些阅读之后,我的android清单文件似乎缺少了一个“service”属性(尽管我尝试过的所有示例都没有此属性);我现在尝试的是
<service
android:name=".LocationService"
android:icon="@drawable/icon"
android:label="@string/service_name"
>
<intent-filter>
<action android:name="android.service.LocationService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>...but还是没有运气。
发布于 2016-05-03 21:23:49
他们创建了这样的服务:
[Service]
public class SimpleService : Service
{
System.Threading.Timer _timer;
public override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug ("SimpleService", "SimpleService started");
DoStuff ();
return StartCommandResult.Sticky;
}
public override void OnDestroy ()
{
base.OnDestroy ();
_timer.Dispose ();
Log.Debug ("SimpleService", "SimpleService stopped");
}
public void DoStuff ()
{
_timer = new System.Threading.Timer ((o) => {
Log.Debug ("SimpleService", "hello from simple service");}
, null, 0, 4000);
}
public override Android.OS.IBinder OnBind (Android.Content.Intent intent)
{
throw new NotImplementedException ();
}
}从这里开始,停止这一切:
StartService (new Intent (this, typeof(SimpleService)));
StopService (new Intent (this, typeof(SimpleService)));而且,听起来你想要一个粘性的服务文档。
当系统面临内存压力时,Android可能会停止任何运行的服务。此规则的例外是在前台显式启动的服务,本文稍后将对此进行讨论。 当服务被系统停止时,Android将使用从OnStartCommand返回的值来确定如何或是否应该重新启动服务。此值的类型为StartCommandResult,可以是以下任意一种:
希望这能有所帮助。
发布于 2016-05-11 11:54:36
现在解决了。这种混淆主要是由于许多样本已经过时(使用过时的方法),以及对于“纯”Android项目和Xamarin项目的不同建议。当然,不需要像我前面建议的那样修改android清单文件。
如果有人想找到类似的东西,我的项目是这里。
当然,解决最初的问题现在提出了一些新的问题,但如果需要的话,我将另行发表。
https://stackoverflow.com/questions/37009705
复制相似问题