活动终止后,Android粘性服务未重新启动

时间:2016-09-09 14:29:58

标签: android xamarin service xamarin.android

我正在开发Xamarin来构建一个启动粘性服务的Android应用程序。 我的问题是,当应用程序处于前台或后台时,服务运行顺畅,但只要我从多任务管理器中删除应用程序就终止应用程序,服务就会停止并且不会重新启动。

以下是活动的代码:

ObservableCollection

服务:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Locations;
using Android.Content;
using Android.Util;
using Android.Runtime;
using System;

namespace TestAppAndroid
{
    [Activity(Label = "TestAppAndroid", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);
            StartService(new Intent(this, typeof(TestService)));
        }
    }
}

如果它可以帮助清单:

using System;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;

namespace TestAppAndroid
{
    [Service]
    public class TestService : Service
    {
        static readonly string TAG = typeof(TestService).Name;
        static readonly int TimerWait = 1000;
        Timer _timer;

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            return StartCommandResult.RedeliverIntent;
        }

        public override void OnCreate()
        {
            base.OnCreate();

            _timer = new Timer(o =>
            {
                Log.Error(TAG, "Hello from simple Service. {0}", DateTime.UtcNow);
            }, null, 0, TimerWait);
        }

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            Log.Error(TAG, "service killed");
        }
    }
}

如果你们在我做错的事情上有任何线索可能真的有帮助! 提前谢谢!

1 个答案:

答案 0 :(得分:2)

请勿触摸Android清单并通过属性定义服务。

问题是:

Xamarin会生成一个AndroidManifest.xml,它是项目的AndroidManifest.xml和使用Activity, Service, ...等属性从声明式样式生成的内容的合并。

这意味着实际AndroidManifest.xml包含服务两次。

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.random.testapp.testappandroid">

    <!-- generated -->
    <service android:name="md5c178831cd46fc53bebc42cf953f78ced.TestService" />

    <!-- manual written -->
    <service android:name=".TestService" android:process=":test_service" android:enabled="true"></service>
</manifest>

您可以查看.\obj\Debug\android\AndroidManifest.xml

进行验证

从项目AndroidManifest.xml中删除该行并使用此服务:

[Service(Enabled = true)]
public class TestService : Service
{
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        return StartCommandResult.Sticky;
    }
    // ...
}

不要使用附加的调试器对其进行测试。我认为杀死应用程序也会杀死这些服务。

相关问题