gpt4 book ai didi

java - Android 加载时的多个 Web 服务调用

转载 作者:行者123 更新时间:2023-12-01 05:48:44 25 4
gpt4 key购买 nike

过去3个月左右我一直在学习Android。不过我还没有遇到过这样的事情。

我想在应用程序首次加载时访问多个不同的 Web 服务。来自这些 Web 服务的响应应进入数据库,以便在应用程序需要时进行检索。我有一个启动屏幕,我试图从中执行此操作:

public class SplashScreen extends BaseActivity {

protected static final int SPLASH_DURATION = 2000;

protected ContactInfoRetriever contactInfoRetriever = new ContactInfoRetriever();

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
startSplashThread();
}

private void startSplashThread() {
Thread splashThread = new Thread() {
@Override
public void run() {
try {
Looper.prepare();
// fire off the calls to the different web services.
updateContactInfo();
updateFooInfo();
updateBarInfo();

int waited = 0;
while (waited < SPLASH_DURATION) {
sleep(100);
waited += 100;
}
}
catch (InterruptedException e) {
Log.e(SplashScreen.class.getSimpleName(), "The splash thread was interrupted.");
}
finally {
finish();
startActivity(new Intent(SplashScreen.this, LandingPageActivity.class));
}
}

};
splashThread.start();
}

protected void updateContactInfo() {

PerformContactInfoSearchTask task = new PerformContactInfoSearchTask();
task.execute();
}

protected void updateFooInfo() {
PerformFooTask task = new PerformFooTask();
task.execute();
}

protected void updateBarInfo() {
PerformBarTask task = new PerformBarTask();
task.execute();
}

private class PerformContactInfoSearchTask extends AsyncTask<String, Void, ContactInfo> {


@Override
protected ContactInfo doInBackground(String... params) {
// this calls a class which calls a web service, and is then passed to an XML parser.
// the result is a ContactInfo object
return contactInfoRetriever.retrieve();
}

@Override
protected void onPostExecute(final ContactInfo result) {
runOnUiThread(new Runnable() {

public void run() {
InsuranceDB db = new InsuranceDB(SplashScreen.this);
// insert the ContactInfo into the DB
db.insertContactInfo(result);
}
});
}

}

private class PerformFooTask extends AsyncTask<String, Void, FooInfo> {
// similar to the PerformContactInfoSearchTask
}

private class PerformBarTask extends AsyncTask<String, Void, BarInfo> {
// similar to the PerformContactInfoSearchTask
}

}

我还没有成功。做这个的最好方式是什么?任务完成后我不需要更新 UI 线程。这是否意味着我应该使用 AsyncTask 以外的其他东西?我读过一些关于 Looper 和 Handler 的内容。这是正确的使用方式吗?任何代码示例都会很棒。

谢谢,扎克

最佳答案

很可能存在竞争条件,因为在等待期结束且 Activity 完成之前 Web 服务调用尚未完成。

更好的方法可能是:

  • 删除等待,finish(),并且startActivity() 从启动画面线程。
  • 合并所有网络服务调用 AsyncTask。
  • 将所有数据库操作移至任务的 doInBackground 方法。
  • 在任务的 onPostExecuteMethod 中,执行以下操作您的完成和 startActivity()。

关于java - Android 加载时的多个 Web 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5238270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com