List of usage examples for android.util SparseArray get
public E get(int key)
null
if no such mapping has been made. From source file:com.ferdi2005.secondgram.NotificationsController.java
public void processReadMessages(final SparseArray<Long> inbox, final long dialog_id, final int max_date, final int max_id, final boolean isPopup) { final ArrayList<MessageObject> popupArray = popupMessages.isEmpty() ? null : new ArrayList<>(popupMessages); notificationsQueue.postRunnable(new Runnable() { @Override/*from w w w .ja v a 2 s .co m*/ public void run() { int oldCount = popupArray != null ? popupArray.size() : 0; if (inbox != null) { for (int b = 0; b < inbox.size(); b++) { int key = inbox.keyAt(b); long messageId = inbox.get(key); for (int a = 0; a < pushMessages.size(); a++) { MessageObject messageObject = pushMessages.get(a); if (messageObject.getDialogId() == key && messageObject.getId() <= (int) messageId) { if (isPersonalMessage(messageObject)) { personal_count--; } if (popupArray != null) { popupArray.remove(messageObject); } long mid = messageObject.messageOwner.id; if (messageObject.messageOwner.to_id.channel_id != 0) { mid |= ((long) messageObject.messageOwner.to_id.channel_id) << 32; } pushMessagesDict.remove(mid); delayedPushMessages.remove(messageObject); pushMessages.remove(a); a--; } } } if (popupArray != null && pushMessages.isEmpty() && !popupArray.isEmpty()) { popupArray.clear(); } } if (dialog_id != 0 && (max_id != 0 || max_date != 0)) { for (int a = 0; a < pushMessages.size(); a++) { MessageObject messageObject = pushMessages.get(a); if (messageObject.getDialogId() == dialog_id) { boolean remove = false; if (max_date != 0) { if (messageObject.messageOwner.date <= max_date) { remove = true; } } else { if (!isPopup) { if (messageObject.getId() <= max_id || max_id < 0) { remove = true; } } else { if (messageObject.getId() == max_id || max_id < 0) { remove = true; } } } if (remove) { if (isPersonalMessage(messageObject)) { personal_count--; } pushMessages.remove(a); delayedPushMessages.remove(messageObject); if (popupArray != null) { popupArray.remove(messageObject); } long mid = messageObject.messageOwner.id; if (messageObject.messageOwner.to_id.channel_id != 0) { mid |= ((long) messageObject.messageOwner.to_id.channel_id) << 32; } pushMessagesDict.remove(mid); a--; } } } if (popupArray != null && pushMessages.isEmpty() && !popupArray.isEmpty()) { popupArray.clear(); } } if (popupArray != null && oldCount != popupArray.size()) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { popupMessages = popupArray; NotificationCenter.getInstance() .postNotificationName(NotificationCenter.pushMessagesUpdated); } }); } } }); }
From source file:com.ferdi2005.secondgram.NotificationsController.java
public void removeDeletedMessagesFromNotifications(final SparseArray<ArrayList<Integer>> deletedMessages) { final ArrayList<MessageObject> popupArray = popupMessages.isEmpty() ? null : new ArrayList<>(popupMessages); notificationsQueue.postRunnable(new Runnable() { @Override/*from ww w .jav a2 s . com*/ public void run() { int old_unread_count = total_unread_count; SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("Notifications", Context.MODE_PRIVATE); for (int a = 0; a < deletedMessages.size(); a++) { int key = deletedMessages.keyAt(a); long dialog_id = -key; ArrayList<Integer> mids = deletedMessages.get(key); Integer currentCount = pushDialogs.get(dialog_id); if (currentCount == null) { currentCount = 0; } Integer newCount = currentCount; for (int b = 0; b < mids.size(); b++) { long mid = mids.get(b); mid |= ((long) key) << 32; MessageObject messageObject = pushMessagesDict.get(mid); if (messageObject != null) { pushMessagesDict.remove(mid); delayedPushMessages.remove(messageObject); pushMessages.remove(messageObject); if (isPersonalMessage(messageObject)) { personal_count--; } if (popupArray != null) { popupArray.remove(messageObject); } newCount--; } } if (newCount <= 0) { newCount = 0; smartNotificationsDialogs.remove(dialog_id); } if (!newCount.equals(currentCount)) { total_unread_count -= currentCount; total_unread_count += newCount; pushDialogs.put(dialog_id, newCount); } if (newCount == 0) { pushDialogs.remove(dialog_id); pushDialogsOverrideMention.remove(dialog_id); if (popupArray != null && pushMessages.isEmpty() && !popupArray.isEmpty()) { popupArray.clear(); } } } if (popupArray != null) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { popupMessages = popupArray; } }); } if (old_unread_count != total_unread_count) { if (!notifyCheck) { delayedPushMessages.clear(); showOrUpdateNotification(notifyCheck); } else { scheduleNotificationDelay( lastOnlineFromOtherDevice > ConnectionsManager.getInstance().getCurrentTime()); } } notifyCheck = false; if (preferences.getBoolean("badgeNumber", true)) { setBadge(total_unread_count); } } }); }
From source file:android.support.design.widget.CoordinatorLayout.java
@Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return;/*from w ww . ja va 2s . c o m*/ } final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); final SparseArray<Parcelable> behaviorStates = ss.behaviorStates; for (int i = 0, count = getChildCount(); i < count; i++) { final View child = getChildAt(i); final int childId = child.getId(); final LayoutParams lp = getResolvedLayoutParams(child); final Behavior b = lp.getBehavior(); if (childId != NO_ID && b != null) { Parcelable savedState = behaviorStates.get(childId); if (savedState != null) { b.onRestoreInstanceState(this, child, savedState); } } } }
From source file:ticwear.design.widget.CoordinatorLayout.java
@Override protected void onRestoreInstanceState(Parcelable state) { final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); final SparseArray<Parcelable> behaviorStates = ss.behaviorStates; for (int i = 0, count = getChildCount(); i < count; i++) { final View child = getChildAt(i); final int childId = child.getId(); final LayoutParams lp = getResolvedLayoutParams(child); final Behavior b = lp.getBehavior(); if (childId != NO_ID && b != null) { Parcelable savedState = behaviorStates.get(childId); if (savedState != null) { b.onRestoreInstanceState(this, child, savedState); }/*from w ww. ja v a2 s . com*/ } } }
From source file:com.fabernovel.alertevoirie.NewsActivity.java
@Override public void onRequestcompleted(int requestCode, Object result) { Log.d(Constants.PROJECT_TAG, "resp : " + result); //@formatter:off /**/*www .j a v a 2 s . co m*/ */ //@formatter:on try { JSONArray responses; responses = new JSONArray((String) result); response = responses.getJSONObject(0); SparseArray<JSONObject> events = new SparseArray<JSONObject>(); if (requestCode == AVService.REQUEST_JSON) { if (JsonData.VALUE_REQUEST_GET_USERS_ACTVITIES.equals(response.getString(JsonData.PARAM_REQUEST))) { lock = new Vector<Integer>(); logs = new SparseArray<JSONObject>(); logList = new TreeMap<String, JSONObject>(Collections.reverseOrder()); JSONArray incidentLog = response.getJSONObject(JsonData.PARAM_ANSWER) .getJSONArray(JsonData.PARAM_INCIDENT_LOG); for (int i = 0; i < incidentLog.length(); i++) { JSONObject job = incidentLog.getJSONObject(i); logs.put(job.getInt(JsonData.ANSWER_INCIDENT_ID), job); logList.put(job.getString(JsonData.PARAM_INCIDENT_DATE) + job.getLong(JsonData.ANSWER_INCIDENT_ID), job); } JSONArray items = new JSONArray(); JSONArray ongoingIncidents = response.getJSONObject(JsonData.PARAM_ANSWER) .getJSONObject(JsonData.PARAM_INCIDENTS).getJSONArray(JsonData.PARAM_ONGOING_INCIDENTS); for (int i = 0; i < ongoingIncidents.length(); i++) { JSONObject job = ongoingIncidents.getJSONObject(i); int key = job.getInt(JsonData.PARAM_INCIDENT_ID); if (logs.get(key) != null) { Log.d("AlerteVoirie_PM", "add ongoing incident " + key); events.put(key, job);// items.put(job); } } JSONArray updatedIncidents = response.getJSONObject(JsonData.PARAM_ANSWER) .getJSONObject(JsonData.PARAM_INCIDENTS).getJSONArray(JsonData.PARAM_UPDATED_INCIDENTS); for (int i = 0; i < updatedIncidents.length(); i++) { JSONObject job = updatedIncidents.getJSONObject(i); int key = job.getInt(JsonData.PARAM_INCIDENT_ID); if (logs.get(key) != null) { Log.d("AlerteVoirie_PM", "add updated incident " + key); events.put(key, job); } } JSONArray resolvedIncidents = response.getJSONObject(JsonData.PARAM_ANSWER) .getJSONObject(JsonData.PARAM_INCIDENTS) .getJSONArray(JsonData.PARAM_RESOLVED_INCIDENTS); for (int i = 0; i < resolvedIncidents.length(); i++) { JSONObject job = resolvedIncidents.getJSONObject(i); int key = job.getInt(JsonData.PARAM_INCIDENT_ID); if (logs.get(key) != null) { Log.d("AlerteVoirie_PM", "add resolved incident " + key); events.put(key, job); } } for (JSONObject log : logList.values()) { int id = log.getInt(JsonData.ANSWER_INCIDENT_ID); Log.d("AlerteVoirie_PM", "key bug " + id); JSONObject jsonObject = events.get(id); if (jsonObject != null) { String json = jsonObject.toString(); JSONObject job = new JSONObject(json); job.put(JsonData.PARAM_INCIDENT_DATE, log.getString(JsonData.PARAM_INCIDENT_DATE)); items.put(job); if (JsonData.PARAM_UPDATE_INCIDENT_INVALID.equals(log.getString(JsonData.PARAM_STATUS)) || JsonData.PARAM_UPDATE_INCIDENT_RESOLVED .equals(log.getString(JsonData.PARAM_STATUS))) { lock.add(id); } } } setListAdapter(new MagicAdapter(this, items, R.layout.cell_report, new String[] { JsonData.PARAM_INCIDENT_DESCRIPTION, JsonData.PARAM_INCIDENT_ADDRESS }, new int[] { R.id.TextView_title, R.id.TextView_text }, null)); } } } catch (JSONException e) { Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : ", e); } catch (ClassCastException e) { Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : CLasscastException", e); } catch (NullPointerException e) { Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : NullPointerException", e); } finally { if (requestCode == AVService.REQUEST_JSON) dismissDialog(DIALOG_PROGRESS); } }
From source file:org.telepatch.ui.ChatActivity.java
@SuppressWarnings("unchecked") @Override/* ww w . ja va 2 s .c om*/ public void didReceivedNotification(int id, final Object... args) { if (id == NotificationCenter.messagesDidLoaded) { long did = (Long) args[0]; if (did == dialog_id) { loadsCount++; int count = (Integer) args[1]; boolean isCache = (Boolean) args[3]; int fnid = (Integer) args[4]; int last_unread_date = (Integer) args[7]; boolean forwardLoad = (Boolean) args[8]; boolean wasUnread = false; boolean positionToUnread = false; if (fnid != 0) { first_unread_id = fnid; last_unread_id = (Integer) args[5]; unread_to_load = (Integer) args[6]; positionToUnread = true; } ArrayList<MessageObject> messArr = (ArrayList<MessageObject>) args[2]; int newRowsCount = 0; unread_end_reached = last_unread_id == 0; if (loadsCount == 1 && messArr.size() > 20) { loadsCount++; } if (firstLoading) { if (!unread_end_reached) { messages.clear(); messagesByDays.clear(); messagesDict.clear(); if (currentEncryptedChat == null) { maxMessageId = Integer.MAX_VALUE; minMessageId = Integer.MIN_VALUE; } else { maxMessageId = Integer.MIN_VALUE; minMessageId = Integer.MAX_VALUE; } maxDate = Integer.MIN_VALUE; minDate = 0; } firstLoading = false; } for (int a = 0; a < messArr.size(); a++) { MessageObject obj = messArr.get(a); if (messagesDict.containsKey(obj.messageOwner.id)) { continue; } if (obj.messageOwner.id > 0) { maxMessageId = Math.min(obj.messageOwner.id, maxMessageId); minMessageId = Math.max(obj.messageOwner.id, minMessageId); } else if (currentEncryptedChat != null) { maxMessageId = Math.max(obj.messageOwner.id, maxMessageId); minMessageId = Math.min(obj.messageOwner.id, minMessageId); } maxDate = Math.max(maxDate, obj.messageOwner.date); if (minDate == 0 || obj.messageOwner.date < minDate) { minDate = obj.messageOwner.date; } if (obj.type < 0) { continue; } if (!obj.isOut() && obj.isUnread()) { wasUnread = true; } messagesDict.put(obj.messageOwner.id, obj); ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey); if (dayArray == null) { dayArray = new ArrayList<MessageObject>(); messagesByDays.put(obj.dateKey, dayArray); TLRPC.Message dateMsg = new TLRPC.Message(); dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date); dateMsg.id = 0; MessageObject dateObj = new MessageObject(dateMsg, null); dateObj.type = 10; dateObj.contentType = 4; if (forwardLoad) { messages.add(0, dateObj); } else { messages.add(dateObj); } newRowsCount++; } newRowsCount++; dayArray.add(obj); if (forwardLoad) { messages.add(0, obj); } else { messages.add(messages.size() - 1, obj); } if (!forwardLoad) { if (obj.messageOwner.id == first_unread_id) { TLRPC.Message dateMsg = new TLRPC.Message(); dateMsg.message = ""; dateMsg.id = 0; MessageObject dateObj = new MessageObject(dateMsg, null); dateObj.contentType = dateObj.type = 6; boolean dateAdded = true; if (a != messArr.size() - 1) { MessageObject next = messArr.get(a + 1); dateAdded = !next.dateKey.equals(obj.dateKey); } messages.add(messages.size() - (dateAdded ? 0 : 1), dateObj); unreadMessageObject = dateObj; newRowsCount++; } if (obj.messageOwner.id == last_unread_id) { unread_end_reached = true; } } } if (unread_end_reached) { first_unread_id = 0; last_unread_id = 0; } if (forwardLoad) { if (messArr.size() != count) { unread_end_reached = true; first_unread_id = 0; last_unread_id = 0; } chatAdapter.notifyDataSetChanged(); loadingForward = false; } else { if (messArr.size() != count) { if (isCache) { cacheEndReaced = true; if (currentEncryptedChat != null || isBroadcast) { endReached = true; } } else { cacheEndReaced = true; endReached = true; } } loading = false; if (chatListView != null) { if (first || scrollToTopOnResume) { chatAdapter.notifyDataSetChanged(); if (positionToUnread && unreadMessageObject != null) { if (messages.get(messages.size() - 1) == unreadMessageObject) { chatListView.setSelectionFromTop(0, AndroidUtilities.dp(-11)); } else { chatListView.setSelectionFromTop( messages.size() - messages.indexOf(unreadMessageObject), AndroidUtilities.dp(-11)); } ViewTreeObserver obs = chatListView.getViewTreeObserver(); obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (!messages.isEmpty()) { if (messages.get(messages.size() - 1) == unreadMessageObject) { chatListView.setSelectionFromTop(0, AndroidUtilities.dp(-11)); } else { chatListView.setSelectionFromTop( messages.size() - messages.indexOf(unreadMessageObject), AndroidUtilities.dp(-11)); } } chatListView.getViewTreeObserver().removeOnPreDrawListener(this); return false; } }); chatListView.invalidate(); showPagedownButton(true, true); } else { chatListView.post(new Runnable() { @Override public void run() { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } }); } } else { int firstVisPos = chatListView.getLastVisiblePosition(); View firstVisView = chatListView.getChildAt(chatListView.getChildCount() - 1); int top = ((firstVisView == null) ? 0 : firstVisView.getTop()) - chatListView.getPaddingTop(); chatAdapter.notifyDataSetChanged(); chatListView.setSelectionFromTop(firstVisPos + newRowsCount - (endReached ? 1 : 0), top); } if (paused) { scrollToTopOnResume = true; if (positionToUnread && unreadMessageObject != null) { scrollToTopUnReadOnResume = true; } } if (first) { if (chatListView.getEmptyView() == null) { chatListView.setEmptyView(emptyViewContainer); } } } else { scrollToTopOnResume = true; if (positionToUnread && unreadMessageObject != null) { scrollToTopUnReadOnResume = true; } } } if (first && messages.size() > 0) { if (last_unread_id != 0) { MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, last_unread_id, 0, last_unread_date, wasUnread, false); } else { MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, wasUnread, false); } first = false; } if (progressView != null) { progressView.setVisibility(View.GONE); } } } else if (id == NotificationCenter.emojiDidLoaded) { if (chatListView != null) { chatListView.invalidateViews(); } } else if (id == NotificationCenter.updateInterfaces) { int updateMask = (Integer) args[0]; if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0) { //TODO non aggiorno niente se sto effettuando una ricerca if (!searching) { updateSubtitle(); updateOnlineCount(); } } if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_NAME) != 0) { checkAndUpdateAvatar(); updateVisibleRows(); } if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) { CharSequence printString = MessagesController.getInstance().printingStrings.get(dialog_id); if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) { //TODO non aggiorno niente se sto effettuando una ricerca if (!searching) { updateSubtitle(); } } } if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) { updateContactStatus(); } } else if (id == NotificationCenter.didReceivedNewMessages) { long did = (Long) args[0]; if (did == dialog_id) { boolean updateChat = false; boolean hasFromMe = false; ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1]; if (currentEncryptedChat != null && arr.size() == 1) { MessageObject obj = arr.get(0); if (currentEncryptedChat != null && obj.isOut() && obj.messageOwner.action != null && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL && getParentActivity() != null) { TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction; if (AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) < 17 && currentEncryptedChat.ttl > 0 && currentEncryptedChat.ttl <= 60) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(R.string.OK, null); builder.setMessage(LocaleController.formatString("CompatibilityChat", R.string.CompatibilityChat, currentUser.first_name, currentUser.first_name)); showAlertDialog(builder); } } } if (!unread_end_reached) { int currentMaxDate = Integer.MIN_VALUE; int currentMinMsgId = Integer.MIN_VALUE; if (currentEncryptedChat != null) { currentMinMsgId = Integer.MAX_VALUE; } boolean currentMarkAsRead = false; for (MessageObject obj : arr) { if (currentEncryptedChat != null && obj.messageOwner.action != null && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL && timerButton != null) { TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction; timerButton.setTime(action.ttl_seconds); } if (obj.isOut() && obj.isSending()) { scrollToLastMessage(); return; } if (messagesDict.containsKey(obj.messageOwner.id)) { continue; } currentMaxDate = Math.max(currentMaxDate, obj.messageOwner.date); if (obj.messageOwner.id > 0) { currentMinMsgId = Math.max(obj.messageOwner.id, currentMinMsgId); } else if (currentEncryptedChat != null) { currentMinMsgId = Math.min(obj.messageOwner.id, currentMinMsgId); } if (!obj.isOut() && obj.isUnread()) { unread_to_load++; currentMarkAsRead = true; } if (obj.type == 10 || obj.type == 11) { updateChat = true; } } if (currentMarkAsRead) { if (paused) { readWhenResume = true; readWithDate = currentMaxDate; readWithMid = currentMinMsgId; } else { if (messages.size() > 0) { MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, currentMinMsgId, 0, currentMaxDate, true, false); } } } updateVisibleRows(); } else { boolean markAsRead = false; int oldCount = messages.size(); for (MessageObject obj : arr) { if (currentEncryptedChat != null && obj.messageOwner.action != null && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL && timerButton != null) { TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction; timerButton.setTime(action.ttl_seconds); } if (messagesDict.containsKey(obj.messageOwner.id)) { continue; } if (minDate == 0 || obj.messageOwner.date < minDate) { minDate = obj.messageOwner.date; } if (obj.isOut()) { removeUnreadPlane(false); hasFromMe = true; } if (!obj.isOut() && unreadMessageObject != null) { unread_to_load++; } if (obj.messageOwner.id > 0) { maxMessageId = Math.min(obj.messageOwner.id, maxMessageId); minMessageId = Math.max(obj.messageOwner.id, minMessageId); } else if (currentEncryptedChat != null) { maxMessageId = Math.max(obj.messageOwner.id, maxMessageId); minMessageId = Math.min(obj.messageOwner.id, minMessageId); } maxDate = Math.max(maxDate, obj.messageOwner.date); messagesDict.put(obj.messageOwner.id, obj); ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey); if (dayArray == null) { dayArray = new ArrayList<MessageObject>(); messagesByDays.put(obj.dateKey, dayArray); TLRPC.Message dateMsg = new TLRPC.Message(); dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date); dateMsg.id = 0; MessageObject dateObj = new MessageObject(dateMsg, null); dateObj.type = 10; dateObj.contentType = 4; messages.add(0, dateObj); } if (!obj.isOut() && obj.isUnread()) { if (!paused) { obj.setIsRead(); } markAsRead = true; } dayArray.add(0, obj); messages.add(0, obj); if (obj.type == 10 || obj.type == 11) { updateChat = true; } } if (progressView != null) { progressView.setVisibility(View.GONE); } if (chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } else { scrollToTopOnResume = true; } if (chatListView != null && chatAdapter != null) { int lastVisible = chatListView.getLastVisiblePosition(); if (endReached) { lastVisible++; } if (lastVisible == oldCount || hasFromMe) { if (!firstLoading) { if (paused) { scrollToTopOnResume = true; } else { chatListView.post(new Runnable() { @Override public void run() { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } }); } } } else { showPagedownButton(true, true); } } else { scrollToTopOnResume = true; } if (markAsRead) { if (paused) { readWhenResume = true; readWithDate = maxDate; readWithMid = minMessageId; } else { MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, true, false); } } } //TODO non aggiorno niente se sto effettuando una ricerca if (updateChat && !searching) { updateSubtitle(); checkAndUpdateAvatar(); } } } else if (id == NotificationCenter.closeChats) { if (args != null && args.length > 0) { long did = (Long) args[0]; if (did == dialog_id) { finishFragment(); } } else { removeSelfFromStack(); } } else if (id == NotificationCenter.messagesRead) { ArrayList<Integer> markAsReadMessages = (ArrayList<Integer>) args[0]; boolean updated = false; for (Integer ids : markAsReadMessages) { MessageObject obj = messagesDict.get(ids); if (obj != null) { obj.setIsRead(); updated = true; } } if (updated) { updateVisibleRows(); } } else if (id == NotificationCenter.messagesDeleted) { ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0]; boolean updated = false; for (Integer ids : markAsDeletedMessages) { MessageObject obj = messagesDict.get(ids); if (obj != null) { int index = messages.indexOf(obj); if (index != -1) { messages.remove(index); messagesDict.remove(ids); ArrayList<MessageObject> dayArr = messagesByDays.get(obj.dateKey); dayArr.remove(obj); if (dayArr.isEmpty()) { messagesByDays.remove(obj.dateKey); messages.remove(index); } updated = true; } } } if (messages.isEmpty()) { if (!endReached && !loading) { progressView.setVisibility(View.GONE); chatListView.setEmptyView(null); if (currentEncryptedChat == null) { maxMessageId = Integer.MAX_VALUE; minMessageId = Integer.MIN_VALUE; } else { maxMessageId = Integer.MIN_VALUE; minMessageId = Integer.MAX_VALUE; } maxDate = Integer.MIN_VALUE; minDate = 0; MessagesController.getInstance().loadMessages(dialog_id, 30, 0, !cacheEndReaced, minDate, classGuid, false, false, null); loading = true; } } if (updated && chatAdapter != null) { removeUnreadPlane(false); chatAdapter.notifyDataSetChanged(); } } else if (id == NotificationCenter.messageReceivedByServer) { Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { Integer newMsgId = (Integer) args[1]; TLRPC.Message newMsgObj = (TLRPC.Message) args[2]; if (newMsgObj != null) { obj.messageOwner.media = newMsgObj.media; obj.generateThumbs(true, 1); } messagesDict.remove(msgId); messagesDict.put(newMsgId, obj); obj.messageOwner.id = newMsgId; obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; updateVisibleRows(); } } else if (id == NotificationCenter.messageReceivedByAck) { Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; updateVisibleRows(); } } else if (id == NotificationCenter.messageSendError) { Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; updateVisibleRows(); } } else if (id == NotificationCenter.chatInfoDidLoaded) { int chatId = (Integer) args[0]; if (currentChat != null && chatId == currentChat.id) { info = (TLRPC.ChatParticipants) args[1]; updateOnlineCount(); if (isBroadcast) { SendMessagesHelper.getInstance().setCurrentChatInfo(info); } } } else if (id == NotificationCenter.contactsDidLoaded) { updateContactStatus(); updateSubtitle(); } else if (id == NotificationCenter.encryptedChatUpdated) { TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) args[0]; if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) { currentEncryptedChat = chat; updateContactStatus(); updateSecretStatus(); } } else if (id == NotificationCenter.messagesReadedEncrypted) { int encId = (Integer) args[0]; if (currentEncryptedChat != null && currentEncryptedChat.id == encId) { int date = (Integer) args[1]; boolean started = false; for (MessageObject obj : messages) { if (!obj.isOut()) { continue; } else if (obj.isOut() && !obj.isUnread()) { break; } if (obj.messageOwner.date <= date) { obj.setIsRead(); } } updateVisibleRows(); } } else if (id == NotificationCenter.audioDidReset) { Integer mid = (Integer) args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatAudioCell) { ChatAudioCell cell = (ChatAudioCell) view; if (cell.getMessageObject() != null && cell.getMessageObject().messageOwner.id == mid) { cell.updateButtonState(); break; } } } } } else if (id == NotificationCenter.audioProgressDidChanged) { Integer mid = (Integer) args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatAudioCell) { ChatAudioCell cell = (ChatAudioCell) view; if (cell.getMessageObject() != null && cell.getMessageObject().messageOwner.id == mid) { cell.updateProgress(); break; } } } } } else if (id == NotificationCenter.removeAllMessagesFromDialog) { long did = (Long) args[0]; if (dialog_id == did) { messages.clear(); messagesByDays.clear(); messagesDict.clear(); progressView.setVisibility(View.GONE); chatListView.setEmptyView(emptyViewContainer); if (currentEncryptedChat == null) { maxMessageId = Integer.MAX_VALUE; minMessageId = Integer.MIN_VALUE; } else { maxMessageId = Integer.MIN_VALUE; minMessageId = Integer.MAX_VALUE; } maxDate = Integer.MIN_VALUE; minDate = 0; selectedMessagesIds.clear(); selectedMessagesCanCopyIds.clear(); actionBarLayer.hideActionMode(); chatAdapter.notifyDataSetChanged(); } } else if (id == NotificationCenter.screenshotTook) { updateInformationForScreenshotDetector(); } else if (id == NotificationCenter.blockedUsersDidLoaded) { if (currentUser != null) { boolean oldValue = userBlocked; userBlocked = MessagesController.getInstance().blockedUsers.contains(currentUser.id); if (oldValue != userBlocked) { updateBottomOverlay(); } } } else if (id == NotificationCenter.FileNewChunkAvailable) { MessageObject messageObject = (MessageObject) args[0]; long finalSize = (Long) args[2]; if (finalSize != 0 && dialog_id == messageObject.getDialogId()) { MessageObject currentObject = messagesDict.get(messageObject.messageOwner.id); if (currentObject != null) { currentObject.messageOwner.media.video.size = (int) finalSize; updateVisibleRows(); } } } else if (id == NotificationCenter.didCreatedNewDeleteTask) { SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>) args[0]; boolean changed = false; for (int i = 0; i < mids.size(); i++) { int key = mids.keyAt(i); ArrayList<Integer> arr = mids.get(key); for (Integer mid : arr) { MessageObject messageObject = messagesDict.get(mid); if (messageObject != null) { messageObject.messageOwner.destroyTime = key; changed = true; } } } if (changed) { updateVisibleRows(); } } else if (id == NotificationCenter.audioDidStarted) { MessageObject messageObject = (MessageObject) args[0]; sendSecretMessageRead(messageObject); } }
From source file:android.support.transition.TransitionPort.java
/** * This method, essentially a wrapper around all calls to createAnimator for all * possible target views, is called with the entire set of start/end * values. The implementation in Transition iterates through these lists * and calls {@link #createAnimator(ViewGroup, TransitionValues, TransitionValues)} * with each set of start/end values on this transition. The * TransitionSet subclass overrides this method and delegates it to * each of its children in succession./*from w w w.j a v a2s . c om*/ * * @hide */ @RestrictTo(GROUP_ID) protected void createAnimators(ViewGroup sceneRoot, TransitionValuesMaps startValues, TransitionValuesMaps endValues) { if (DBG) { Log.d(LOG_TAG, "createAnimators() for " + this); } ArrayMap<View, TransitionValues> endCopy = new ArrayMap<>(endValues.viewValues); SparseArray<TransitionValues> endIdCopy = new SparseArray<>(endValues.idValues.size()); for (int i = 0; i < endValues.idValues.size(); ++i) { int id = endValues.idValues.keyAt(i); endIdCopy.put(id, endValues.idValues.valueAt(i)); } LongSparseArray<TransitionValues> endItemIdCopy = new LongSparseArray<>(endValues.itemIdValues.size()); for (int i = 0; i < endValues.itemIdValues.size(); ++i) { long id = endValues.itemIdValues.keyAt(i); endItemIdCopy.put(id, endValues.itemIdValues.valueAt(i)); } // Walk through the start values, playing everything we find // Remove from the end set as we go ArrayList<TransitionValues> startValuesList = new ArrayList<>(); ArrayList<TransitionValues> endValuesList = new ArrayList<>(); for (View view : startValues.viewValues.keySet()) { TransitionValues start; TransitionValues end = null; boolean isInListView = false; if (view.getParent() instanceof ListView) { isInListView = true; } if (!isInListView) { int id = view.getId(); start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view) : startValues.idValues.get(id); if (endValues.viewValues.get(view) != null) { end = endValues.viewValues.get(view); endCopy.remove(view); } else if (id != View.NO_ID) { end = endValues.idValues.get(id); View removeView = null; for (View viewToRemove : endCopy.keySet()) { if (viewToRemove.getId() == id) { removeView = viewToRemove; } } if (removeView != null) { endCopy.remove(removeView); } } endIdCopy.remove(id); if (isValidTarget(view, id)) { startValuesList.add(start); endValuesList.add(end); } } else { ListView parent = (ListView) view.getParent(); if (parent.getAdapter().hasStableIds()) { int position = parent.getPositionForView(view); long itemId = parent.getItemIdAtPosition(position); start = startValues.itemIdValues.get(itemId); endItemIdCopy.remove(itemId); // TODO: deal with targetIDs for itemIDs for ListView items startValuesList.add(start); endValuesList.add(end); } } } int startItemIdCopySize = startValues.itemIdValues.size(); for (int i = 0; i < startItemIdCopySize; ++i) { long id = startValues.itemIdValues.keyAt(i); if (isValidTarget(null, id)) { TransitionValues start = startValues.itemIdValues.get(id); TransitionValues end = endValues.itemIdValues.get(id); endItemIdCopy.remove(id); startValuesList.add(start); endValuesList.add(end); } } // Now walk through the remains of the end set for (View view : endCopy.keySet()) { int id = view.getId(); if (isValidTarget(view, id)) { TransitionValues start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view) : startValues.idValues.get(id); TransitionValues end = endCopy.get(view); endIdCopy.remove(id); startValuesList.add(start); endValuesList.add(end); } } int endIdCopySize = endIdCopy.size(); for (int i = 0; i < endIdCopySize; ++i) { int id = endIdCopy.keyAt(i); if (isValidTarget(null, id)) { TransitionValues start = startValues.idValues.get(id); TransitionValues end = endIdCopy.get(id); startValuesList.add(start); endValuesList.add(end); } } int endItemIdCopySize = endItemIdCopy.size(); for (int i = 0; i < endItemIdCopySize; ++i) { long id = endItemIdCopy.keyAt(i); // TODO: Deal with targetIDs and itemIDs TransitionValues start = startValues.itemIdValues.get(id); TransitionValues end = endItemIdCopy.get(id); startValuesList.add(start); endValuesList.add(end); } ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators(); for (int i = 0; i < startValuesList.size(); ++i) { TransitionValues start = startValuesList.get(i); TransitionValues end = endValuesList.get(i); // Only bother trying to animate with values that differ between start/end if (start != null || end != null) { if (start == null || !start.equals(end)) { if (DBG) { View view = (end != null) ? end.view : start.view; Log.d(LOG_TAG, " differing start/end values for view " + view); if (start == null || end == null) { Log.d(LOG_TAG, " " + ((start == null) ? "start null, end non-null" : "start non-null, end null")); } else { for (String key : start.values.keySet()) { Object startValue = start.values.get(key); Object endValue = end.values.get(key); if (startValue != endValue && !startValue.equals(endValue)) { Log.d(LOG_TAG, " " + key + ": start(" + startValue + "), end(" + endValue + ")"); } } } } // TODO: what to do about targetIds and itemIds? Animator animator = createAnimator(sceneRoot, start, end); if (animator != null) { // Save animation info for future cancellation purposes View view; TransitionValues infoValues = null; if (end != null) { view = end.view; String[] properties = getTransitionProperties(); if (view != null && properties != null && properties.length > 0) { infoValues = new TransitionValues(); infoValues.view = view; TransitionValues newValues = endValues.viewValues.get(view); if (newValues != null) { for (int j = 0; j < properties.length; ++j) { infoValues.values.put(properties[j], newValues.values.get(properties[j])); } } int numExistingAnims = runningAnimators.size(); for (int j = 0; j < numExistingAnims; ++j) { Animator anim = runningAnimators.keyAt(j); AnimationInfo info = runningAnimators.get(anim); if (info.values != null && info.view == view && ((info.name == null && getName() == null) || info.name.equals(getName()))) { if (info.values.equals(infoValues)) { // Favor the old animator animator = null; break; } } } } } else { view = start.view; } if (animator != null) { AnimationInfo info = new AnimationInfo(view, getName(), WindowIdPort.getWindowId(sceneRoot), infoValues); runningAnimators.put(animator, info); mAnimators.add(animator); } } } } } }
From source file:android.support.transition.Transition.java
/** * This method, essentially a wrapper around all calls to createAnimator for all * possible target views, is called with the entire set of start/end * values. The implementation in Transition iterates through these lists * and calls {@link #createAnimator(android.view.ViewGroup, android.support.transition.TransitionValues, android.support.transition.TransitionValues)} * with each set of start/end values on this transition. The * TransitionSet subclass overrides this method and delegates it to * each of its children in succession./*from ww w. j a va 2s . c o m*/ * * @hide */ protected void createAnimators(ViewGroup sceneRoot, TransitionValuesMaps startValues, TransitionValuesMaps endValues) { if (DBG) { Log.d(LOG_TAG, "createAnimators() for " + this); } ArrayMap<View, TransitionValues> endCopy = new ArrayMap<View, TransitionValues>(endValues.viewValues); SparseArray<TransitionValues> endIdCopy = new SparseArray<TransitionValues>(endValues.idValues.size()); for (int i = 0; i < endValues.idValues.size(); ++i) { int id = endValues.idValues.keyAt(i); endIdCopy.put(id, endValues.idValues.valueAt(i)); } LongSparseArray<TransitionValues> endItemIdCopy = new LongSparseArray<TransitionValues>( endValues.itemIdValues.size()); for (int i = 0; i < endValues.itemIdValues.size(); ++i) { long id = endValues.itemIdValues.keyAt(i); endItemIdCopy.put(id, endValues.itemIdValues.valueAt(i)); } // Walk through the start values, playing everything we find // Remove from the end set as we go ArrayList<TransitionValues> startValuesList = new ArrayList<TransitionValues>(); ArrayList<TransitionValues> endValuesList = new ArrayList<TransitionValues>(); for (View view : startValues.viewValues.keySet()) { TransitionValues start = null; TransitionValues end = null; boolean isInListView = false; if (view.getParent() instanceof ListView) { isInListView = true; } if (!isInListView) { int id = view.getId(); start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view) : startValues.idValues.get(id); if (endValues.viewValues.get(view) != null) { end = endValues.viewValues.get(view); endCopy.remove(view); } else if (id != View.NO_ID) { end = endValues.idValues.get(id); View removeView = null; for (View viewToRemove : endCopy.keySet()) { if (viewToRemove.getId() == id) { removeView = viewToRemove; } } if (removeView != null) { endCopy.remove(removeView); } } endIdCopy.remove(id); if (isValidTarget(view, id)) { startValuesList.add(start); endValuesList.add(end); } } else { ListView parent = (ListView) view.getParent(); if (parent.getAdapter().hasStableIds()) { int position = parent.getPositionForView(view); long itemId = parent.getItemIdAtPosition(position); start = startValues.itemIdValues.get(itemId); endItemIdCopy.remove(itemId); // TODO: deal with targetIDs for itemIDs for ListView items startValuesList.add(start); endValuesList.add(end); } } } int startItemIdCopySize = startValues.itemIdValues.size(); for (int i = 0; i < startItemIdCopySize; ++i) { long id = startValues.itemIdValues.keyAt(i); if (isValidTarget(null, id)) { TransitionValues start = startValues.itemIdValues.get(id); TransitionValues end = endValues.itemIdValues.get(id); endItemIdCopy.remove(id); startValuesList.add(start); endValuesList.add(end); } } // Now walk through the remains of the end set for (View view : endCopy.keySet()) { int id = view.getId(); if (isValidTarget(view, id)) { TransitionValues start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view) : startValues.idValues.get(id); TransitionValues end = endCopy.get(view); endIdCopy.remove(id); startValuesList.add(start); endValuesList.add(end); } } int endIdCopySize = endIdCopy.size(); for (int i = 0; i < endIdCopySize; ++i) { int id = endIdCopy.keyAt(i); if (isValidTarget(null, id)) { TransitionValues start = startValues.idValues.get(id); TransitionValues end = endIdCopy.get(id); startValuesList.add(start); endValuesList.add(end); } } int endItemIdCopySize = endItemIdCopy.size(); for (int i = 0; i < endItemIdCopySize; ++i) { long id = endItemIdCopy.keyAt(i); // TODO: Deal with targetIDs and itemIDs TransitionValues start = startValues.itemIdValues.get(id); TransitionValues end = endItemIdCopy.get(id); startValuesList.add(start); endValuesList.add(end); } ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators(); for (int i = 0; i < startValuesList.size(); ++i) { TransitionValues start = startValuesList.get(i); TransitionValues end = endValuesList.get(i); // Only bother trying to animate with values that differ between start/end if (start != null || end != null) { if (start == null || !start.equals(end)) { if (DBG) { View view = (end != null) ? end.view : start.view; Log.d(LOG_TAG, " differing start/end values for view " + view); if (start == null || end == null) { Log.d(LOG_TAG, " " + ((start == null) ? "start null, end non-null" : "start non-null, end null")); } else { for (String key : start.values.keySet()) { Object startValue = start.values.get(key); Object endValue = end.values.get(key); if (startValue != endValue && !startValue.equals(endValue)) { Log.d(LOG_TAG, " " + key + ": start(" + startValue + "), end(" + endValue + ")"); } } } } // TODO: what to do about targetIds and itemIds? Animator animator = createAnimator(sceneRoot, start, end); if (animator != null) { // Save animation info for future cancellation purposes View view = null; TransitionValues infoValues = null; if (end != null) { view = end.view; String[] properties = getTransitionProperties(); if (view != null && properties != null && properties.length > 0) { infoValues = new TransitionValues(); infoValues.view = view; TransitionValues newValues = endValues.viewValues.get(view); if (newValues != null) { for (int j = 0; j < properties.length; ++j) { infoValues.values.put(properties[j], newValues.values.get(properties[j])); } } int numExistingAnims = runningAnimators.size(); for (int j = 0; j < numExistingAnims; ++j) { Animator anim = runningAnimators.keyAt(j); AnimationInfo info = runningAnimators.get(anim); if (info.values != null && info.view == view && ((info.name == null && getName() == null) || info.name.equals(getName()))) { if (info.values.equals(infoValues)) { // Favor the old animator animator = null; break; } } } } } else { view = (start != null) ? start.view : null; } if (animator != null) { AnimationInfo info = new AnimationInfo(view, getName(), infoValues); runningAnimators.put(animator, info); mAnimators.add(animator); } } } } } }
From source file:org.tvbrowser.tvbrowser.TvBrowser.java
private void uploadChannels() { String[] projection = { TvBrowserContentProvider.GROUP_KEY_GROUP_ID, TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID, TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER }; Cursor channels = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_CHANNELS, projection, TvBrowserContentProvider.CHANNEL_KEY_SELECTION, null, TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER); SparseArray<String> groupKeys = new SparseArray<String>(); StringBuilder uploadChannels = new StringBuilder(); try {/*from w w w.j a va 2s . c o m*/ channels.moveToPosition(-1); int groupKeyColumn = channels.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_GROUP_ID); int channelKeyColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID); int channelKeyOrderNumberColumn = channels .getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER); while (channels.moveToNext()) { int groupKey = channels.getInt(groupKeyColumn); String channelId = channels.getString(channelKeyColumn); int orderNumber = channels.getInt(channelKeyOrderNumberColumn); String groupId = groupKeys.get(groupKey); if (groupId == null) { String[] groupProjection = { TvBrowserContentProvider.GROUP_KEY_GROUP_ID, TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID }; Cursor groups = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_GROUPS, groupProjection, TvBrowserContentProvider.KEY_ID + "=" + groupKey, null, null); try { if (groups.moveToFirst()) { String dataServiceId = groups.getString( groups.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID)); String goupIdValue = groups .getString(groups.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_GROUP_ID)); String dataServiceIdNumber = SettingConstants.getNumberForDataServiceKey(dataServiceId); if (dataServiceIdNumber != null) { if (dataServiceId.equals(SettingConstants.EPG_FREE_KEY)) { groupId = dataServiceIdNumber + ":" + goupIdValue + ":"; } else if (dataServiceId.equals(SettingConstants.EPG_DONATE_KEY)) { groupId = dataServiceIdNumber + ":"; } groupKeys.put(groupKey, groupId); } } } finally { groups.close(); } } uploadChannels.append(groupId).append(channelId); if (orderNumber > 0) { uploadChannels.append(":").append(orderNumber); } uploadChannels.append("\n"); } } finally { channels.close(); } if (uploadChannels.toString().trim().length() > 0) { startSynchronizeUp(true, uploadChannels.toString().trim(), "http://android.tvbrowser.org/data/scripts/syncUp.php?type=channelsFromDesktop", SettingConstants.SYNCHRONIZE_UP_DONE, getString(R.string.backup_channels_success)); } }
From source file:com.android.messaging.mmslib.pdu.PduPersister.java
/** * Persist a PDU object to specific location in the storage. * * @param pdu The PDU object to be stored. * @param uri Where to store the given PDU object. * @param subId Subscription id associated with this message. * @param subPhoneNumber TODO/*from w ww .j a v a2 s . co m*/ * @param preOpenedFiles if not null, a map of preopened InputStreams for the parts. * @return A Uri which can be used to access the stored PDU. */ public Uri persist(final GenericPdu pdu, final Uri uri, final int subId, final String subPhoneNumber, final Map<Uri, InputStream> preOpenedFiles) throws MmsException { if (uri == null) { throw new MmsException("Uri may not be null."); } long msgId = -1; try { msgId = ContentUris.parseId(uri); } catch (final NumberFormatException e) { // the uri ends with "inbox" or something else like that } final boolean existingUri = msgId != -1; if (!existingUri && MESSAGE_BOX_MAP.get(uri) == null) { throw new MmsException("Bad destination, must be one of " + "content://mms/inbox, content://mms/sent, " + "content://mms/drafts, content://mms/outbox, " + "content://mms/temp."); } synchronized (PDU_CACHE_INSTANCE) { // If the cache item is getting updated, wait until it's done updating before // purging it. if (PDU_CACHE_INSTANCE.isUpdating(uri)) { if (LOCAL_LOGV) { LogUtil.v(TAG, "persist: " + uri + " blocked by isUpdating()"); } try { PDU_CACHE_INSTANCE.wait(); } catch (final InterruptedException e) { Log.e(TAG, "persist1: ", e); } } } PDU_CACHE_INSTANCE.purge(uri); final PduHeaders header = pdu.getPduHeaders(); PduBody body = null; ContentValues values = new ContentValues(); // Mark new messages as seen in the telephony database so that we don't have to // do a global "set all messages as seen" since that occasionally seems to be // problematic (i.e. very slow). See bug 18189471. values.put(Mms.SEEN, 1); //Set<Entry<Integer, String>> set; for (int i = ENCODED_STRING_COLUMN_NAME_MAP.size(); --i >= 0;) { final int field = ENCODED_STRING_COLUMN_NAME_MAP.keyAt(i); final EncodedStringValue encodedString = header.getEncodedStringValue(field); if (encodedString != null) { final String charsetColumn = CHARSET_COLUMN_NAME_MAP.get(field); values.put(ENCODED_STRING_COLUMN_NAME_MAP.valueAt(i), toIsoString(encodedString.getTextString())); values.put(charsetColumn, encodedString.getCharacterSet()); } } for (int i = TEXT_STRING_COLUMN_NAME_MAP.size(); --i >= 0;) { final byte[] text = header.getTextString(TEXT_STRING_COLUMN_NAME_MAP.keyAt(i)); if (text != null) { values.put(TEXT_STRING_COLUMN_NAME_MAP.valueAt(i), toIsoString(text)); } } for (int i = OCTET_COLUMN_NAME_MAP.size(); --i >= 0;) { final int b = header.getOctet(OCTET_COLUMN_NAME_MAP.keyAt(i)); if (b != 0) { values.put(OCTET_COLUMN_NAME_MAP.valueAt(i), b); } } for (int i = LONG_COLUMN_NAME_MAP.size(); --i >= 0;) { final long l = header.getLongInteger(LONG_COLUMN_NAME_MAP.keyAt(i)); if (l != -1L) { values.put(LONG_COLUMN_NAME_MAP.valueAt(i), l); } } final SparseArray<EncodedStringValue[]> addressMap = new SparseArray<EncodedStringValue[]>( ADDRESS_FIELDS.length); // Save address information. for (final int addrType : ADDRESS_FIELDS) { EncodedStringValue[] array = null; if (addrType == PduHeaders.FROM) { final EncodedStringValue v = header.getEncodedStringValue(addrType); if (v != null) { array = new EncodedStringValue[1]; array[0] = v; } } else { array = header.getEncodedStringValues(addrType); } addressMap.put(addrType, array); } final HashSet<String> recipients = new HashSet<String>(); final int msgType = pdu.getMessageType(); // Here we only allocate thread ID for M-Notification.ind, // M-Retrieve.conf and M-Send.req. // Some of other PDU types may be allocated a thread ID outside // this scope. if ((msgType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) || (msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF) || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) { switch (msgType) { case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND: case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF: loadRecipients(PduHeaders.FROM, recipients, addressMap); // For received messages (whether group MMS is enabled or not) we want to // associate this message with the thread composed of all the recipients // EXCLUDING our own number. This includes the person who sent the // message (the FROM field above) in addition to the other people the message // was addressed TO (or CC fields to address group messaging compatibility // issues with devices that place numbers in this field). Typically our own // number is in the TO/CC field so we have to remove it in loadRecipients. checkAndLoadToCcRecipients(recipients, addressMap, subPhoneNumber); break; case PduHeaders.MESSAGE_TYPE_SEND_REQ: loadRecipients(PduHeaders.TO, recipients, addressMap); break; } long threadId = -1L; if (!recipients.isEmpty()) { // Given all the recipients associated with this message, find (or create) the // correct thread. threadId = MmsSmsUtils.Threads.getOrCreateThreadId(mContext, recipients); } else { LogUtil.w(TAG, "PduPersister.persist No recipients; persisting PDU to thread: " + threadId); } values.put(Mms.THREAD_ID, threadId); } // Save parts first to avoid inconsistent message is loaded // while saving the parts. final long dummyId = System.currentTimeMillis(); // Dummy ID of the msg. // Figure out if this PDU is a text-only message boolean textOnly = true; // Get body if the PDU is a RetrieveConf or SendReq. if (pdu instanceof MultimediaMessagePdu) { body = ((MultimediaMessagePdu) pdu).getBody(); // Start saving parts if necessary. if (body != null) { final int partsNum = body.getPartsNum(); if (LOCAL_LOGV) { LogUtil.v(TAG, "PduPersister.persist partsNum: " + partsNum); } if (partsNum > 2) { // For a text-only message there will be two parts: 1-the SMIL, 2-the text. // Down a few lines below we're checking to make sure we've only got SMIL or // text. We also have to check then we don't have more than two parts. // Otherwise, a slideshow with two text slides would be marked as textOnly. textOnly = false; } for (int i = 0; i < partsNum; i++) { final PduPart part = body.getPart(i); persistPart(part, dummyId, preOpenedFiles); // If we've got anything besides text/plain or SMIL part, then we've got // an mms message with some other type of attachment. final String contentType = getPartContentType(part); if (LOCAL_LOGV) { LogUtil.v(TAG, "PduPersister.persist part: " + i + " contentType: " + contentType); } if (contentType != null && !ContentType.APP_SMIL.equals(contentType) && !ContentType.TEXT_PLAIN.equals(contentType)) { textOnly = false; } } } } // Record whether this mms message is a simple plain text or not. This is a hint for the // UI. if (OsUtil.isAtLeastJB_MR1()) { values.put(Mms.TEXT_ONLY, textOnly ? 1 : 0); } if (OsUtil.isAtLeastL_MR1()) { values.put(Mms.SUBSCRIPTION_ID, subId); } else { Assert.equals(ParticipantData.DEFAULT_SELF_SUB_ID, subId); } Uri res = null; if (existingUri) { res = uri; SqliteWrapper.update(mContext, mContentResolver, res, values, null, null); } else { res = SqliteWrapper.insert(mContext, mContentResolver, uri, values); if (res == null) { throw new MmsException("persist() failed: return null."); } // Get the real ID of the PDU and update all parts which were // saved with the dummy ID. msgId = ContentUris.parseId(res); } values = new ContentValues(1); values.put(Part.MSG_ID, msgId); SqliteWrapper.update(mContext, mContentResolver, Uri.parse("content://mms/" + dummyId + "/part"), values, null, null); // We should return the longest URI of the persisted PDU, for // example, if input URI is "content://mms/inbox" and the _ID of // persisted PDU is '8', we should return "content://mms/inbox/8" // instead of "content://mms/8". // TODO: Should the MmsProvider be responsible for this??? if (!existingUri) { res = Uri.parse(uri + "/" + msgId); } // Save address information. for (final int addrType : ADDRESS_FIELDS) { final EncodedStringValue[] array = addressMap.get(addrType); if (array != null) { persistAddress(msgId, addrType, array); } } return res; }