当用户登录移动应用程序时,我要在数据库中插入一些数据。以及我还有其他一些服务呼叫,这使我的应用程序登录最糟糕。 因此,在这里我想知道如何立即登录并在后台继续执行其他数据服务。
但是我拨打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();
};
答案 0 :(得分:3)
Android提供了JobService类,您可以在其中从JobScheduler类安排JobService。 JobScheduler在后台运行该服务,您可以继续登录。 您可以在这里找到一个Xamarin示例: https://blog.xamarin.com/replacing-services-jobs-android-oreo-8-0/
创建一个JobService类,并将您的InsertPushKeys代码添加到OnStartJob函数中。 确保在“新线程”上启动它。
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");
}
确保在另一个线程上运行任务。
答案 1 :(得分:1)
这就是您要寻找的。服务是Android框架提供的一种结构,可以完全满足您的需求。有关更多信息,请检查-
http://www.vogella.com/tutorials/AndroidServices/article.html
TLDR :将API调用放入服务的onCreate()
和return START_STICKY
的{{1}}中。不要忘记在服务实例上调用onStartCommand()
。
答案 2 :(得分:1)
在Task.Run
内部调用服务,而无需使用await关键字。 Await保持控制直到完成全部执行。使用await关键字可能会向您发出警告,但您可以忽略它。
Task.Run(async () =>
{
InsertPushKeys();
});
&请勿在保持执行的方法结尾尝试使用.Wait()
(直到需要它)。