Я пытаюсь обновить ListView onReceive BroadcastReceiver. В моей основной деятельности, которая содержит ListView, о которой я говорю, я регистрирую получателя:
private final BroadcastReceiver smsIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String mAction = intent.getAction();
if(mAction.equals(INCOMING_SMS_ACTION)) {
Log.v(runtimeVars.getMyName(), "reloading conversation list");
curConversation = managedQuery(conversationURI, null, null, null, "date DESC");
conversationAdapter = null;
listConversations();
}
}
};
listConversations() выглядит так
private void listConversations() {
Uri smsURI;
Uri personURI;
Cursor curSms;
Cursor curPerson;
long personID;
curConversation = managedQuery(conversationURI, null, null, null, "date DESC");
conversationArrayList = new ArrayList<ConversationListObj>();
this.conversationAdapter = new ConversationListAdapter(this, R.layout.conversationlist_item, conversationArrayList);
setListAdapter(this.conversationAdapter);
Log.v(runtimeVars.getMyName(), "listConversations");
startManagingCursor(curConversation);
for(curConversation.moveToFirst(); !curConversation.isAfterLast(); curConversation.moveToNext()) {
smsURI = Uri.parse("content://sms/conversations/" + curConversation.getString(curConversation.getColumnIndexOrThrow("thread_id")).toString());
curSms = managedQuery(smsURI, null, null, null, null);
conversationArrayList = new ArrayList<ConversationListObj>();
ConversationListObj newListObj = new ConversationListObj();
newListObj.setThreadID(curConversation.getString(curConversation.getColumnIndexOrThrow("thread_id")).toString());
if (curSms.moveToFirst()) {
personURI = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(curSms.getString(curSms.getColumnIndex("address"))));
curPerson = managedQuery(personURI, new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
startManagingCursor(curPerson);
if(curPerson.moveToFirst()) {
personID = Long.parseLong(curPerson.getString(curPerson.getColumnIndex(ContactsContract.PhoneLookup._ID)));
Bitmap contactPicture = generalMethods.loadContactPhoto(getContentResolver(), personID);
if (contactPicture != null)
newListObj.setSenderPicture(contactPicture);
else {
InputStream input = this.getResources().openRawResource(R.drawable.person_dummy);
newListObj.setSenderPicture(BitmapFactory.decodeStream(input));
}
newListObj.setSenderName(curPerson.getString(curPerson.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)));
}
else {
newListObj.setSenderName(curSms.getString(curSms.getColumnIndex("address")));
}
newListObj.setMessagePart(curConversation.getString(curConversation.getColumnIndexOrThrow("snippet")).toString());
conversationArrayList.add(newListObj);
notifyConversationAdapter();
}
}
curConversation.close();
}
Теперь, когда я получаю SMS, кажется, что мой BroadcastReceiver был слишком быстрым. Новое текстовое сообщение не появится, пока я не перезапущу приложение. Поэтому я в основном думаю, что я сделал ошибку дизайна, но как бы это было правильно? Просмотр файла журнала сообщает мне
08-29 13:08:44.351: VERBOSE/SotapannaSMS(704): reloading conversation list
08-29 13:08:45.091: VERBOSE/SotapannaSMS(704): listConversations
08-29 13:08:45.921: VERBOSE/Telephony(171): getOrCreateThreadId uri: content://mms-sms/threadID?recipient=5556
08-29 13:08:46.081: INFO/NotificationService(59): enqueueToast pkg=info.SotapannaSMS.messaging callback=android.app.ITransientNotification$Stub$Proxy@43dbff88 duration=0
08-29 13:08:46.571: VERBOSE/Telephony(171): getOrCreateThreadId cursor cnt: 1
Новое текстовое сообщение, похоже, не находится в этом разговоре, пока я не перезапущу приложение. Я даже пытался позволить своему приложению спать в течение 3 секунд, чтобы увидеть, будет ли просто ждать бит, но это закончилось тем же результатом.
Что мне не хватает?
Android хранит сообщение только после завершения onReceive.
Если вы спящий вызов onReceive в течение 2 секунд, то сообщение будет сохранено через 2 секунды. Покрутите новую нить и спать там. Ваш onReceive должен вернуться как можно скорее.
Источник: LogCat