【发布时间】:2011-07-11 10:19:45
【问题描述】:
在过去 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 的东西。这是正确的使用方法吗?任何代码示例都会很棒。
谢谢, 扎克
【问题讨论】:
标签: java android multithreading web-services sqlite