直到AsyncTask完成后才会显示ProgressDialog

时间:2010-04-24 08:56:11

标签: android android-asynctask progressdialog

我正在尝试显示无限期的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);
    }
}

1 个答案:

答案 0 :(得分:0)

请勿bindService()执行doInBackground()。首先,它几乎是即时的,因此您不需要将它放在后台线程中 - 您所做的只是浪费CPU时间和电池。其次,它需要使用Looper的{​​{1}}和消息队列,因此将它放在后台线程中是危险的恕我直言。

另请注意,您既绑定了服务又启动了服务。在某些情况下这是合适的,但通常只需要一个或另一个。

相关问题