我在Xamarin.Forms中有一个应用程序,我开发了一个仅在应用程序打开或最小化时才有效的服务。 我添加了一些日志,即使应用程序关闭,服务也会继续运行,但我的部分代码在Portable上运行不会。
Code MainActivity
var alarmIntent = new Intent(context.ApplicationContext, typeof(Receiver.AlarmReceiver));
var broadcast = PendingIntent.GetBroadcast(context.ApplicationContext, 0, alarmIntent, PendingIntentFlags.NoCreate);
if (broadcast == null)
{
var pendingIntent = PendingIntent.GetBroadcast(context.ApplicationContext, 0, alarmIntent, 0);
var alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
alarmManager.SetRepeating(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime(), 15000, pendingIntent);
}
代码警报接收器
[BroadcastReceiver]
class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var backgroundServiceIntent = new Intent(context, typeof(ServiceBackground));
context.StartService(backgroundServiceIntent);
}
}
代码服务
[Service]
public class ServiceBackground : Service
{
private const string TAG = "[ServiceBackground]";
private bool _isRunning;
private Context _context;
private Task _task;
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
_context = this;
_isRunning = false;
_task = new Task(RunServiceBackground);
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
if (!_isRunning)
{
_isRunning = true;
_task.Start();
}
return StartCommandResult.Sticky;
}
private void RunServiceBackground()
{
Log.Info(TAG, "StartCommandResult");
Task.Run(() =>
{
try
{
Log.Info(TAG, "init background portable");
var serviceOrdersSvc = new ServiceOrdersService();
serviceOrdersSvc.BackgroundExecute()
.ContinueWith(itemResult => {
if (!string.IsNullOrEmpty(itemResult.Result))
{
Log.Info(TAG, "itemResult");
}
});
}
catch (Android.OS.OperationCanceledException ex)
{
Log.Info(TAG, $"ex msg: {ex.Message} | s: {ex.StackTrace}");
}
catch (Exception ex)
{
Log.Info(TAG, $"ex msg: {ex.Message} | s: {ex.StackTrace}");
}
finally
{
StopSelf();
}
});
}
public override void OnDestroy()
{
base.OnDestroy();
}
}
代码可移植(此部分不起作用)
public async Task<string> BackgroundExecute()
{
//insert sqllite
await LogService.InsertLogAsync("init - BackgroundExecute");
//get sqllite
var list = await BackgroundTaskRequest.GetListAsync();
var rtnBackground = "";
if (list != null && list.Count > 0)
{
LogService.InsertLogAsync("list count: " + list.Count.ToString());
await Task.Run(async () =>
{
foreach (var item in list)
{
//send information web-api
}
});
}
LogService.InsertLogAsync($"end rtn: {rtnBackground}");
return rtnBackground;
}
我在这里缺少什么?