我试图显示一个不确定的 ProgressDialog,而 AsyncTask 绑定到 RemoteService。首次创建服务时,RemoteService 会构建用户联系人列表。对于一长串联系人,这可能需要 5~10 秒。
我遇到的问题是,在 RemoteService 建立它的联系人列表之前,ProgressDialog 不会显示。我什至尝试放入一个 Thread.sleep 以让 ProgressDialog 有时间显示。使用 sleep 语句,ProgressDialog 加载并开始旋转,但一旦 RemoteService 开始工作,就会锁定。
如果我只是将 AsyncTask 变成虚拟代码,让它休眠一会儿,一切正常。但是当任务必须做实际工作时,就像 UI 只是坐着等待。
关于我做错了什么的任何想法?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(IM,"Start Me UP!!");
setContentView(R.layout.main);
Log.d(IM, "Building List View for Contacts");
restoreMe();
if (myContacts==null){
myContacts = new ArrayList<Contact>();
this.contactAdapter = new ContactAdapter(this,
R.layout.contactlist,
myContacts);
setListAdapter(this.contactAdapter);
new BindAsync().execute();
}
else{
this.contactAdapter = new ContactAdapter(this,
R.layout.contactlist,
myContacts);
setListAdapter(this.contactAdapter);
}
}
private class BindAsync extends AsyncTask<Void, Void, RemoteServiceConnection>{
@Override
protected void onPreExecute(){
super.onPreExecute();
Log.d(IM,"Showing Dialog");
showDialog(DIALOG_CONTACTS);
}
@Override
protected RemoteServiceConnection doInBackground(Void... v) {
Log.d(IM,"Binding to service in BindAsync");
try{
Thread.sleep(2000);
} catch (InterruptedException e){
}
RemoteServiceConnection myCon;
myCon = new RemoteServiceConnection();
Intent i = new Intent(imandroid.this,MyRemoteService.class);
bindService(i, myCon, Context.BIND_AUTO_CREATE);
startService(i);
Log.d(IM,"Bound to remote service");
return myCon;
}
@Override
protected void onPostExecute(RemoteServiceConnection newConn){
super.onPostExecute(newConn);
Log.d(IM,"Storing remote connection");
conn=newConn;
}
};
编辑:添加 onCreateDialog
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_CONTACTS:
ProgressDialog progDialog = new ProgressDialog(imandroid.this);
progDialog.setMessage("Loading Contacts... Please Wait");
progDialog.setCancelable(false);
return progDialog;
default:
return super.onCreateDialog(id);
}
}