过去3个月左右我一直在学习Android。但是,我还没有遇到过这样的事情。
我想在最初加载应用程序时访问几个不同的Web服务。这些Web服务的响应应该进入DB以便在应用程序中需要时进行检索。我有一个闪屏,我试图这样做:
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的内容。这是正确的用法吗?任何代码示例都很精彩。
谢谢, 扎克
答案 0 :(得分:0)
您很可能遇到竞争条件,因为在等待期结束和活动结束之前,Web服务调用尚未完成。
更好的方法可能是:
HTH