我有一个FetchConvoinBackground
的内部类extends AsyncTask
,在doInBackGround()
方法中,我将其称为retrieveConversations()
。 retrieveConversations()
方法的代码段为;
private void retrieveConversations() {
ContentResolver cr = getContentResolver();
Uri uri = Uri.parse("content://sms/conversations/");
Cursor convoCursor = cr.query(uri, new String[]{"thread_id","snippet"}, null,null,"date DESC");
String convoID; //ID of the convo
String snippet; // the heading SMS of the convo
convoCursor.moveToFirst();
for(int i=0;i<convoCursor.getCount();i++) {
//try {
// Thread.sleep(200);
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
conversation = new Conversation();
convoID = convoCursor.getString(convoCursor.getColumnIndex("thread_id"));
snippet = convoCursor.getString(convoCursor.getColumnIndex("snippet"));
String[] nameNumber = getConvoSenderNameNumber(convoID);
if(nameNumber[1].equals("")){ //if nameNumber[1]=="", then the associated thread has no received message.
convoCursor.moveToNext();
continue;
}
//which has only two indeces; 0 for name, 1 for Number
conversation.put(convoID, nameNumber[0], nameNumber[1], snippet); //getConvoSenderNameNumber() returns nameNumber array of strings
Log.d("Async sender",""+conversation.sender);
mainHandler.post(new Runnable() {
@Override
public void run() {
Log.d("main UI sender",""+conversation.sender);
conversationList.add(conversation);
adapter.notifyDataSetChanged();
}
});
convoCursor.moveToNext();
}
convoCursor.close();
}
在当前代码布局下,如果retrieveConversations()
的{{1}}调用了doInBackGround()
,则必须平稳运行代码,直到使用AsyncTask
方法,然后在{ {1}}方法,因此必须将mainHandler.post()
的更新值放入mainHandler.post()'s run()
(conversationList是conversation
类的ArrayList)。但是不幸的是事实并非如此。对话的值写在conversationList
之前的代码中,但是在Conversation
中有时将值mainHandler.post()
放入mainHandler.post()
中,有时将先前的值放入,或者有时将null
被跳过。
当我使用conversationsList
(低于200时,会发生与上述相同的问题),一切正常,但要花很多时间。 如何mainHandler.post()
是Thread.sleep(200)
,直到成功写入mainHandler.post()
,然后再写入wait()
,直到将其成功放入{{1} }