c#xamarin - 关闭应用程序时关闭Android后台服务

时间:2016-08-07 17:09:48

标签: c# android

关闭主要活动时,我的Android服务关闭了。 我尝试添加到AndroidManifest.xml:<service android:name="App7.SimpleService" android:stopWithTask="false">

我还尝试了以下代码来启动服务:

Intent intent2 = new Intent(ApplicationContext, typeof(SimpleService));
 StartService(intent2);

 StartService(new Intent("App7.SimpleService"));

我还尝试了return START_STICKY;return StartCommandResult.Sticky;,但没有效果。

我的代码: 的 SimpleService.cs:

    using System;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using Android.Widget;
using Android;
using App7;
using static System.Net.Mime.MediaTypeNames;
using System.Threading.Tasks;
using System.Text;

namespace SimpleService
{
    [Service]
    [IntentFilter(new String[] { "App7.SimpleService" })]
    public class SimpleServiceBinder : Service
    {


        public static StartCommandResult START_STICKY { get; private set; }




        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
        /// My service code
            return StartCommandResult.Sticky;
        }

        public override IBinder OnBind(Intent intent)
        {
   //         binder = new SimpleService(this);
           return null;
        }

        public override void OnDestroy()
        {


        base.OnDestroy();




        }


    }
}

MainActivity.cs:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using App7;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using Android.Webkit;
using System.Threading.Tasks;

namespace SimpleService
{
    [Activity(Label = "aplikacja1", MainLauncher = true)]
    [Service]

    public class MainActivity : Activity
    {

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

                //////////////////////////////////////
                this.StartService(new Intent(this, typeof(SimpleServiceBinder)));
               /// I tried also////

              // Intent intent2 = new Intent(ApplicationContext, typeof(SimpleService));
                //  StartService(intent2);
               // StartService(new Intent("App7.SimpleService"));



        }
    }
}

请帮帮我

0 个答案:

没有答案