在Xamarin Android中关闭应用程序后,后台服务停止

时间:2017-06-01 14:22:54

标签: android xamarin.android

我是Xamarin开发的新手。我创建了一个后台服务,用于跟踪用户位置。它正常工作,直到应用程序运行/打开。当应用程序关闭/销毁时,我的后台服务停止工作。我已经花了很多时间找出这个问题背后的原因。但运气不好。

[Service]
public class LocationTrackingService : Service, GoogleApiClient.IConnectionCallbacks,
    GoogleApiClient.IOnConnectionFailedListener, Android.Gms.Location.ILocationListener
{
    protected const string TAG = "Attendance Frag";
    protected const int REQUEST_CHECK_SETTINGS = 0x1;
    public const long UPDATE_INTERVAL_IN_MILLISECONDS = 20 * 1000;
    public const long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    protected const string KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
    protected const string KEY_LOCATION = "location";
    protected const string KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";

    protected GoogleApiClient mGoogleApiClient;
    protected LocationRequest mLocationRequest;
    protected LocationSettingsRequest mLocationSettingsRequest;


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

        Toast.MakeText(this, "OnCreate", ToastLength.Short).Show();
    }

    protected void BuildGoogleApiClient()
    {
        Log.Info("AttendanceFrag", "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .AddConnectionCallbacks(this)
            .AddOnConnectionFailedListener(this)
            .AddApi(LocationServices.API)
            .Build();
    }

    protected void CreateLocationRequest()
    {
        mLocationRequest = new LocationRequest();
        mLocationRequest.SetInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.SetFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
    }

    protected void BuildLocationSettingsRequest()
    {
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.AddLocationRequest(mLocationRequest);
        builder.SetAlwaysShow(true);
        mLocationSettingsRequest = builder.Build();
    }

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

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

        if (mGoogleApiClient != null && !mGoogleApiClient.IsConnected)
            mGoogleApiClient.Connect();

        return StartCommandResult.Sticky;
    }


    protected async Task StartLocationUpdates()
    {
        await LocationServices.FusedLocationApi.RequestLocationUpdates(
            mGoogleApiClient,
            mLocationRequest,
            this
        );
    }

    protected async Task StopLocationUpdates()
    {
        await LocationServices.FusedLocationApi.RemoveLocationUpdates(
                mGoogleApiClient,
                this
            );
    }

    public async void OnConnected(Bundle connectionHint)
    {
        Log.Info(TAG, "Connected to GoogleApiClient");

        await StartLocationUpdates();
    }

    public void OnConnectionSuspended(int cause)
    {
        Log.Info(TAG, "Connection suspended");
    }

    public void OnConnectionFailed(Android.Gms.Common.ConnectionResult result)
    {
        Log.Info(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.ErrorCode);
    }

    public void OnLocationChanged(Location location)
    {
        Toast.MakeText(this, "OnLocationChanged", ToastLength.Short).Show();

    }

    public override async void OnDestroy()
    {
        base.OnDestroy();
        Toast.MakeText(this, "OnDestroy", ToastLength.Short).Show();
        if (mGoogleApiClient != null
            && mGoogleApiClient.IsConnected)
        {
            await StopLocationUpdates();
        }

        //Start GeoLocation Tracking Service again
        Intent i = new Intent(this, typeof(RestartServiceReceiver));
        i.SetAction(RestartServiceReceiver.START_TRACKING);
        SendBroadcast(i);

    }
}

请帮帮我

2 个答案:

答案 0 :(得分:0)

在像这样的私人流程中启动您的服务

[Service(Name = "com.xamarin.TimestampService", 
         Process=":timestampservice_process", 
         Exported=true)]

有关在流程here中运行服务的更多信息。 您也可以将其注册为foreground service,这样他们就不会被Android停下来并显示在通知栏中

答案 1 :(得分:0)

抱歉回复晚了,但我认为它可以帮助其他人。我想向您明确说明您正在将此服务作为后台服务编写。后台服务不能长时间运行。 Android 8.0以后的Android后台服务有一些限制。一段时间后,Android 会自动终止应用的后台服务。

看到这个https://developer.android.com/about/versions/oreo/background

如果你想长时间运行一个服务,那就把服务设为前台服务。请按照 https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services 详细了解 Xamarin Forms 中的前台服务。