异步方法在android后台服务xamarin中不起作用

时间:2018-06-27 08:04:21

标签: c# android xamarin xamarin.android background-process

我正在使用以下代码

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


public static int ConvertMinutesToMilliseconds(int minutes)
{
    return (int)TimeSpan.FromMinutes(minutes).TotalMilliseconds;
}
System.Threading.Timer _timer;
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
    DoWork();
    _timer = new System.Threading.Timer((o) => {
      SyncStepsToApi();
    }, null, 0, 20000);

    return StartCommandResult.Sticky;
}


public async void SyncStepsToApi()
        {
            SaveEmployeeActivities saveEmployeeActivities = new SaveEmployeeActivities();

            saveEmployeeActivities.AuthenticationToken = APICalling.authToken;
            saveEmployeeActivities.Steps =await db.GetUserSteps();
           var numberOfActivitiesModified= await ServiceClient.SaveUserActivity(saveEmployeeActivities);
            Notification.Builder notificationBuilder = new Notification.Builder(this)
          .SetSmallIcon(Resource.Drawable.screen)
          .SetContentTitle("perkit service notification")
          .SetContentText(numberOfActivitiesModified.NoOfActivitiesModified.ToString());

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.Notify(19000, notificationBuilder.Build());
        }

要在后台运行服务,除SyncStepsToApi();以外,其他所有功能都可以正常运行,只有当应用程序保持在前台状态时,此方法才会调用。 当我关闭应用程序服务时,除正常运行外,在syncsteptoapi(db.getusersteps)中返回0条记录。

0 个答案:

没有答案