当用户登录移动应用程序时,我有一些数据要插入数据库。以及我也有一些其他服务调用,这使我的应用程序登录最糟糕。 所以在这里我想知道如何立即登录并在后台继续执行其他数据服务。
但是我正在进行 async
调用,这似乎不起作用。
我进行的服务调用是否在后台运行?或者我可以让它更面糊
private async Task InsertPushKeys()
{
foreach (var item in SISConst.Mychildren)
{
pushInfo.OrganizationId = Convert.ToInt64(item.OrganizationID);
pushInfo.OsType = "Android";
pushInfo.ServerkeyPush = SISConst.LmgKey;
var ignore = await logDAL.InsertPushInfo(pushInfo);
}
}
下行执行服务。
var ignore = await logDAL.InsertPushInfo(pushInfo);
编辑 1:我在登录按钮内以相同的顺序调用这些服务
_btnSignUp.Click += async (s, e) =>
{
var loggedInUser = await uLogin.UserLogin(_inputName.Text.Trim(), _inputPassword.Text);
Task.Run(async () => { mychildList = await uLogin.BindMychildrenGridData(result.UserID); }).Wait();
await DeletePushKeys(loggedInUser.UserID);
InsertPushKeys();
};
最佳答案
Android 提供了 JobService 类,您可以在其中从 JobScheduler 类调度 JobService。 JobScheduler 在后台运行该服务,您可以继续登录。 您可以在此处找到一个 Xamarin 示例: https://blog.xamarin.com/replacing-services-jobs-android-oreo-8-0/
创建一个 JobService 类并在 OnStartJob 函数中添加 InsertPushKeys 代码。 确保在新线程上启动它。
OnStartJob(JobParameters parameters){
new Thread(new Runnable() {
public void run() {
await InsertPushKeys();
}
}).start();
}
现在使用 JobInfo 类构建作业,如上面的链接所示:
ComponentName componentName = new ComponentName(this, MyJobService.class);
JobInfo jobInfo = new JobInfo.Builder(12, componentName)
.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.build();
最后,您可以安排您的作业,它会由 android 执行。
JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Console.WriteLine(TAG, "Job scheduled!");
} else {
Console.WriteLine(TAG, "Job not scheduled");
}
确保在不同的线程上运行任务。
关于c# - 使用应用程序 Xamarin Android 时继续在后台执行服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51842226/