下面列出了android.util.LongSparseArray#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Adds a new entry to the cache.
*
* @param key a key that uniquely identifies the entry
* @param theme the theme against which this entry was inflated, or
* {@code null} if the entry has no theme applied
* @param entry the entry to cache
* @param usesTheme {@code true} if the entry is affected theme changes,
* {@code false} otherwise
*/
public void put(long key, @Nullable Theme theme, @NonNull T entry, boolean usesTheme) {
if (entry == null) {
return;
}
synchronized (this) {
final LongSparseArray<WeakReference<T>> entries;
if (!usesTheme) {
entries = getUnthemedLocked(true);
} else {
entries = getThemedLocked(theme, true);
}
if (entries != null) {
entries.put(key, new WeakReference<>(entry));
}
}
}
private LongSparseArray<ThumbnailInfo> queryThumbnailInfoList() {
ContentResolver resolver = getContext().getApplicationContext().getContentResolver();
Uri uri = MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI;
LongSparseArray<ThumbnailInfo> result = new LongSparseArray<>();
try (Cursor cursor = resolver.query(uri, null,
null, null, null)) {
if (cursor == null) {
return result;
}
if (cursor.moveToFirst()) {
do {
ThumbnailInfo info = createThumbnailInfo(cursor);
result.put(info.getId(), info);
} while (cursor.moveToNext());
}
return result;
}
}
private boolean importWorkspace() throws Exception {
ArrayList<Long> allScreens = LauncherDbUtils.getScreenIdsFromCursor(
mContext.getContentResolver().query(mOtherScreensUri, null, null, null,
LauncherSettings.WorkspaceScreens.SCREEN_RANK));
// During import we reset the screen IDs to 0-indexed values.
if (allScreens.isEmpty()) {
// No thing to migrate
return false;
}
mHotseatSize = mMaxGridSizeX = mMaxGridSizeY = 0;
// Build screen update
ArrayList<ContentProviderOperation> screenOps = new ArrayList<>();
int count = allScreens.size();
LongSparseArray<Long> screenIdMap = new LongSparseArray<>(count);
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
v.put(LauncherSettings.WorkspaceScreens._ID, i);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
screenIdMap.put(allScreens.get(i), (long) i);
screenOps.add(ContentProviderOperation.newInsert(
LauncherSettings.WorkspaceScreens.CONTENT_URI).withValues(v).build());
}
mContext.getContentResolver().applyBatch(ProviderConfig.AUTHORITY, screenOps);
importWorkspaceItems(allScreens.get(0), screenIdMap);
GridSizeMigrationTask.markForMigration(mContext, mMaxGridSizeX, mMaxGridSizeY, mHotseatSize);
// Create empty DB flag.
LauncherSettings.Settings.call(mContext.getContentResolver(),
LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
return true;
}
/**
* Builds a map of available channels.
*
* @param resolver Application's ContentResolver.
* @param inputId The ID of the TV input service that provides this TV channel.
* @return LongSparseArray mapping each channel's {@link Channels#_ID} to the Channel object.
* @hide
*/
public static LongSparseArray<Channel> buildChannelMap(
@NonNull ContentResolver resolver, @NonNull String inputId) {
Uri uri = TvContract.buildChannelsUriForInput(inputId);
LongSparseArray<Channel> channelMap = new LongSparseArray<>();
Cursor cursor = null;
try {
cursor = resolver.query(uri, Channel.PROJECTION, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
if (DEBUG) {
Log.d(TAG, "Cursor is null or found no results");
}
return null;
}
while (cursor.moveToNext()) {
Channel nextChannel = Channel.fromCursor(cursor);
channelMap.put(nextChannel.getId(), nextChannel);
}
} catch (Exception e) {
Log.d(TAG, "Content provider query: " + Arrays.toString(e.getStackTrace()));
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
return channelMap;
}
public static LongSparseArray<Channel> buildChannelMap(ContentResolver resolver,
String inputId, List<Channel> channels) {
Uri uri = TvContract.buildChannelsUriForInput(inputId);
String[] projection = {
TvContract.Channels._ID,
TvContract.Channels.COLUMN_DISPLAY_NUMBER
};
LongSparseArray<Channel> channelMap = new LongSparseArray<>();
Cursor cursor = null;
try {
cursor = resolver.query(uri, projection, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
return null;
}
while (cursor.moveToNext()) {
long channelId = cursor.getLong(0);
Log.d(TAG, "BUILD CHANNELS FOR "+channelId);
String channelNumber = cursor.getString(1);
channelMap.put(channelId, getChannelByNumber(channelNumber, channels));
}
} catch (Exception e) {
Log.d(TAG, "Content provider query: " + e.getStackTrace());
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
return channelMap;
}
/**
* Builds a map of available channels.
*
* @param resolver Application's ContentResolver.
* @param inputId The ID of the TV input service that provides this TV channel.
* @return LongSparseArray mapping each channel's {@link Channels#_ID} to the Channel object.
* @hide
*/
public static LongSparseArray<Channel> buildChannelMap(
@NonNull ContentResolver resolver, @NonNull String inputId) {
Uri uri = TvContract.buildChannelsUriForInput(inputId);
LongSparseArray<Channel> channelMap = new LongSparseArray<>();
Cursor cursor = null;
try {
cursor = resolver.query(uri, Channel.PROJECTION, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
if (DEBUG) {
Log.d(TAG, "Cursor is null or found no results");
}
return null;
}
while (cursor.moveToNext()) {
Channel nextChannel = Channel.fromCursor(cursor);
channelMap.put(nextChannel.getId(), nextChannel);
}
} catch (Exception e) {
Log.d(TAG, "Content provider query: " + Arrays.toString(e.getStackTrace()));
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
return channelMap;
}
/**
* Caches an {@link AccessibilityNodeInfo}.
*
* @param info The node to cache.
*/
public void add(AccessibilityNodeInfo info) {
synchronized(mLock) {
if (DEBUG) {
Log.i(LOG_TAG, "add(" + info + ")");
}
final int windowId = info.getWindowId();
LongSparseArray<AccessibilityNodeInfo> nodes = mNodeCache.get(windowId);
if (nodes == null) {
nodes = new LongSparseArray<>();
mNodeCache.put(windowId, nodes);
}
final long sourceId = info.getSourceNodeId();
AccessibilityNodeInfo oldInfo = nodes.get(sourceId);
if (oldInfo != null) {
// If the added node is in the cache we have to be careful if
// the new one represents a source state where some of the
// children have been removed to remove the descendants that
// are no longer present.
final LongArray newChildrenIds = info.getChildNodeIds();
final int oldChildCount = oldInfo.getChildCount();
for (int i = 0; i < oldChildCount; i++) {
if (nodes.get(sourceId) == null) {
// We've removed (and thus recycled) this node because it was its own
// ancestor (the app gave us bad data), we can't continue using it.
// Clear the cache for this window and give up on adding the node.
clearNodesForWindowLocked(windowId);
return;
}
final long oldChildId = oldInfo.getChildId(i);
// If the child is no longer present, remove the sub-tree.
if (newChildrenIds == null || newChildrenIds.indexOf(oldChildId) < 0) {
clearSubTreeLocked(windowId, oldChildId);
}
}
// Also be careful if the parent has changed since the new
// parent may be a predecessor of the old parent which will
// add cycles to the cache.
final long oldParentId = oldInfo.getParentNodeId();
if (info.getParentNodeId() != oldParentId) {
clearSubTreeLocked(windowId, oldParentId);
} else {
oldInfo.recycle();
}
}
// Cache a copy since the client calls to AccessibilityNodeInfo#recycle()
// will wipe the data of the cached info.
AccessibilityNodeInfo clone = AccessibilityNodeInfo.obtain(info);
nodes.put(sourceId, clone);
if (clone.isAccessibilityFocused()) {
mAccessibilityFocus = sourceId;
}
if (clone.isFocused()) {
mInputFocus = sourceId;
}
}
}
private void enforceNodeTreeConsistent(List<AccessibilityNodeInfo> nodes) {
LongSparseArray<AccessibilityNodeInfo> nodeMap =
new LongSparseArray<AccessibilityNodeInfo>();
final int nodeCount = nodes.size();
for (int i = 0; i < nodeCount; i++) {
AccessibilityNodeInfo node = nodes.get(i);
nodeMap.put(node.getSourceNodeId(), node);
}
// If the nodes are a tree it does not matter from
// which node we start to search for the root.
AccessibilityNodeInfo root = nodeMap.valueAt(0);
AccessibilityNodeInfo parent = root;
while (parent != null) {
root = parent;
parent = nodeMap.get(parent.getParentNodeId());
}
// Traverse the tree and do some checks.
AccessibilityNodeInfo accessFocus = null;
AccessibilityNodeInfo inputFocus = null;
HashSet<AccessibilityNodeInfo> seen = new HashSet<AccessibilityNodeInfo>();
Queue<AccessibilityNodeInfo> fringe = new LinkedList<AccessibilityNodeInfo>();
fringe.add(root);
while (!fringe.isEmpty()) {
AccessibilityNodeInfo current = fringe.poll();
// Check for duplicates
if (!seen.add(current)) {
throw new IllegalStateException("Duplicate node: "
+ current + " in window:"
+ mViewRootImpl.mAttachInfo.mAccessibilityWindowId);
}
// Check for one accessibility focus.
if (current.isAccessibilityFocused()) {
if (accessFocus != null) {
throw new IllegalStateException("Duplicate accessibility focus:"
+ current
+ " in window:" + mViewRootImpl.mAttachInfo.mAccessibilityWindowId);
} else {
accessFocus = current;
}
}
// Check for one input focus.
if (current.isFocused()) {
if (inputFocus != null) {
throw new IllegalStateException("Duplicate input focus: "
+ current + " in window:"
+ mViewRootImpl.mAttachInfo.mAccessibilityWindowId);
} else {
inputFocus = current;
}
}
final int childCount = current.getChildCount();
for (int j = 0; j < childCount; j++) {
final long childId = current.getChildId(j);
final AccessibilityNodeInfo child = nodeMap.get(childId);
if (child != null) {
fringe.add(child);
}
}
}
// Check for disconnected nodes.
for (int j = nodeMap.size() - 1; j >= 0; j--) {
AccessibilityNodeInfo info = nodeMap.valueAt(j);
if (!seen.contains(info)) {
throw new IllegalStateException("Disconnected node: " + info);
}
}
}
public LongSparseArray<ContactModel> fetchContacts() {
LongSparseArray<ContactModel> contacts = new LongSparseArray<>();
Cursor cursor = createCursor();
cursor.moveToFirst();
// get column indexes
int idxId = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
int idxPrimaryName = cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
int idxStarred = cursor.getColumnIndex(ContactsContract.Data.STARRED);
int idxphoto = cursor.getColumnIndex(ContactsContract.Data.PHOTO_URI);
int idxMimetype = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
int idxData1 = cursor.getColumnIndex(ContactsContract.Data.DATA1);
while (!cursor.isAfterLast()) {
// get the id and the contact for this id. The contact may be null
long id = cursor.getLong(idxId);
ContactModel contact = contacts.get(id, null);
if (contact == null) {
// create a new contact
contact = new ContactModel(id);
mapDisplayName(cursor, contact, idxPrimaryName);
mapPhoto(cursor, contact, idxphoto);
mapStarred(cursor, contact, idxStarred);
contacts.put(id, contact);
}
int idxPhoneNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// Log.d("Parzival", "Data: "+cursor.getString(idxPhoneNumber));
// map email or phone numbers
String mimeType = cursor.getString(idxMimetype);
switch (mimeType) {
case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE: {
mapEmail(cursor, contact, idxData1);
break;
}
case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE: {
mapPhoneNumbers(cursor, contact, idxData1);
break;
}
}
cursor.moveToNext();
}
cursor.close();
return contacts;
}
@Nullable MessagingStyle buildFromArchive(final Conversation conversation, final Notification n, final CharSequence title, final List<StatusBarNotification> archive) {
// Chat history in big content view
if (archive.isEmpty()) {
Log.d(TAG, "No history");
return null;
}
final LongSparseArray<Pair<CharSequence/* text */, CharSequence/* ticker */>> lines = new LongSparseArray<>(MAX_NUM_HISTORICAL_LINES);
int count = 0, num_lines_with_colon = 0;
final String redundant_prefix = title.toString() + SENDER_MESSAGE_SEPARATOR;
for (final StatusBarNotification each : archive) {
final Notification notification = each.getNotification();
final Bundle its_extras = notification.extras;
final CharSequence its_title = EmojiTranslator.translate(its_extras.getCharSequence(Notification.EXTRA_TITLE));
if (! title.equals(its_title)) {
Log.d(TAG, "Skip other conversation with the same key in archive: " + its_title); // ID reset by WeChat due to notification removal in previous evolving
continue;
}
final CharSequence its_text = its_extras.getCharSequence(EXTRA_TEXT);
if (its_text == null) {
Log.w(TAG, "No text in archived notification.");
continue;
}
final int result = trimAndExtractLeadingCounter(its_text);
if (result >= 0) {
count = result & 0xFFFF;
CharSequence trimmed_text = its_text.subSequence(result >> 16, its_text.length());
if (trimmed_text.toString().startsWith(redundant_prefix)) // Remove redundant prefix
trimmed_text = trimmed_text.subSequence(redundant_prefix.length(), trimmed_text.length());
else if (trimmed_text.toString().indexOf(SENDER_MESSAGE_SEPARATOR) > 0) num_lines_with_colon ++;
lines.put(notification.when, new Pair<>(trimmed_text, notification.tickerText));
} else {
count = 1;
lines.put(notification.when, new Pair<>(its_text, n.tickerText));
if (its_text.toString().indexOf(SENDER_MESSAGE_SEPARATOR) > 0) num_lines_with_colon ++;
}
}
n.number = count;
if (lines.size() == 0) {
Log.w(TAG, "No lines extracted, expected " + count);
return null;
}
final MessagingStyle messaging = new MessagingStyle(mUserSelf);
final boolean sender_inline = num_lines_with_colon == lines.size();
for (int i = 0, size = lines.size(); i < size; i ++) { // All lines have colon in text
final Pair<CharSequence/* Text */, CharSequence/* Ticker */> line = lines.valueAt(i);
messaging.addMessage(buildMessage(conversation, lines.keyAt(i), line.second, line.first, sender_inline ? null : title.toString()));
}
return messaging;
}
private void fetch (LimitColumn columnLimitChoice, ObservableEmitter emitter) {
LongSparseArray<Contact> contacts = new LongSparseArray<>();
Cursor cursor = createCursor(getFilter(columnLimitChoice));
cursor.moveToFirst();
int idColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
int inVisibleGroupColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.IN_VISIBLE_GROUP);
int displayNamePrimaryColumnIndex = cursor.getColumnIndex(DISPLAY_NAME);
int starredColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.STARRED);
int photoColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_URI);
int thumbnailColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI);
int hasPhoneNumberColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
while (!cursor.isAfterLast()) {
long id = cursor.getLong(idColumnIndex);
Contact contact = contacts.get(id, null);
if (contact == null) {
contact = new Contact(id);
}
ColumnMapper.mapInVisibleGroup(cursor, contact, inVisibleGroupColumnIndex);
ColumnMapper.mapDisplayName(cursor, contact, displayNamePrimaryColumnIndex);
ColumnMapper.mapStarred(cursor, contact, starredColumnIndex);
ColumnMapper.mapPhoto(cursor, contact, photoColumnIndex);
ColumnMapper.mapThumbnail(cursor, contact, thumbnailColumnIndex);
switch (columnLimitChoice){
case EMAIL:
getEmail(id, contact);
break;
case PHONE:
getPhoneNumber(id, cursor, contact, hasPhoneNumberColumnIndex);
break;
case NONE:
getEmail(id, contact);
getPhoneNumber(id, cursor, contact, hasPhoneNumberColumnIndex);
break;
}
if(columnLimitChoice == LimitColumn.EMAIL){
if(contact.getEmails().size() > 0){
contacts.put(id, contact);
//noinspection unchecked
emitter.onNext(contact);
}
}else{
contacts.put(id, contact);
//noinspection unchecked
emitter.onNext(contact);
}
cursor.moveToNext();
}
cursor.close();
emitter.onComplete();
}