即使应用已关闭,如何运行android服务

时间:2018-09-17 09:43:37

标签: android xamarin xamarin.forms xamarin.android

我创建了一个简单的应用,该应用使用Xamarin使用GPS保存用户的位置。这已经在做。

  1. 用户使用应用程序时。保存位置确定。
  2. 当用户最小化应用程序时。保存位置可以。

但是当用户关闭应用程序时。保存位置不正确。首先是我使用了 IntentService ,但仍然无法正常工作,所以我尝试了 Service

下面是我的代码段。

广播接收器

[BroadcastReceiver]
public class MyAlarmReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {

        var serviceIntent = new Intent(context, typeof(MyReverseGeoCodeLocationService));
        serviceIntent.PutExtras(intent);
        context.StartService(serviceIntent);

    }
}

服务

[Service]
class MyReverseGeoCodeLocationService : Android.App.Service
{
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

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

    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        new System.Threading.Tasks.Task(() =>
        {
            CurrentLocationService obj = new CurrentLocationService(new MyLocalStorageService(), this.ApplicationContext);
            obj.OnTimedEvent();

        }).Start();

        return StartCommandResult.Sticky;
    }
}

MainActivity

var alarmIntent = new Intent(this, typeof(MyAlarmReceiver));
var pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);


var alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
alarmManager.SetInexactRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime(), 120000, pending);

1 个答案:

答案 0 :(得分:0)

您可以在android中使用Alarms。 看这个页面: https://developer.android.com/training/scheduling/alarms

相关问题