下面列出了怎么用android.util.SparseIntArray的API类实例代码及写法,或者点击链接到github查看源代码。
public void setSpecialInterval(JSONObject jsonObject) {
if (jsonObject != null) {
this.mSpecialInterval = new SparseIntArray();
for (String key : jsonObject.keySet()) {
try {
int index = Integer.parseInt(key);
int value = jsonObject.getIntValue(key);
if (value > 0) {
this.mSpecialInterval.put(index, value);
}
} catch (Exception e) {
}
}
}
}
private void syncFirewallChainLocked(int chain, String name) {
SparseIntArray rules;
synchronized (mRulesLock) {
final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
// Make a copy of the current rules, and then clear them. This is because
// setFirewallUidRuleInternal only pushes down rules to the native daemon if they
// are different from the current rules stored in the mUidFirewall*Rules array for
// the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
// will do nothing.
rules = uidFirewallRules.clone();
uidFirewallRules.clear();
}
if (rules.size() > 0) {
// Now push the rules. setFirewallUidRuleInternal will push each of these down to the
// native daemon, and also add them to the mUidFirewall*Rules array for the specified
// chain.
if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
+ name + "UID rules");
for (int i = 0; i < rules.size(); i++) {
setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
}
}
}
private void writeLineText(SpannableStringBuilder builder, BidiLine line) {
SparseIntArray visualMap = new SparseIntArray();
int counter = 1;
for (BidiRun bidiRun : line.getVisualRuns()) {
visualMap.put(bidiRun.charStart, counter);
counter++;
}
int runCount = visualMap.size();
if (runCount > 0) {
appendText(builder, "Visual Order\n", spansSecondHeading());
for (int i = 0; i < runCount; i++) {
int runIndex = visualMap.valueAt(i);
appendText(builder, "<Run " + runIndex + ">", spansInlineHeading());
appendText(builder, " ");
}
appendText(builder, "\n\n");
}
}
public static void saveArrayPref(SharedPreferencesContainer container, SparseIntArray intArray) {
JSONArray json = new JSONArray();
StringBuilder data = new StringBuilder().append("[");
for (int i = 0; i < intArray.size(); i++) {
data.append("{")
.append("\"key\": ")
.append(intArray.keyAt(i)).append(",")
.append("\"value\": ")
.append(intArray.valueAt(i))
.append("},");
json.put(data);
}
data.deleteCharAt(data.length() - 1);
data.append("]");
container.putString(PREF_KEY, intArray.size() == 0 ? null : data.toString());
container.apply();
}
/** Get the list of publically visible output formats; does not include IMPL_DEFINED */
private int[] getPublicFormats(boolean output) {
int[] formats = new int[getPublicFormatCount(output)];
int i = 0;
SparseIntArray map = getFormatsMap(output);
for (int j = 0; j < map.size(); j++) {
int format = map.keyAt(j);
formats[i++] = imageFormatToPublic(format);
}
if (output) {
for (int j = 0; j < mDepthOutputFormats.size(); j++) {
formats[i++] = depthFormatToPublic(mDepthOutputFormats.keyAt(j));
}
}
if (formats.length != i) {
throw new AssertionError("Too few formats " + i + ", expected " + formats.length);
}
return formats;
}
@Override
public Object[] getSections() {
positionOfSection = new SparseIntArray();
sectionOfPosition = new SparseIntArray();
int count = getCount();
list = new ArrayList<String>();
list.add(getContext().getString(R.string.search_header));
positionOfSection.put(0, 0);
sectionOfPosition.put(0, 0);
for (int i = 1; i < count; i++) {
String letter = getItem(i).getHeader();
System.err.println("contactadapter getsection getHeader:" + letter
+ " name:" + getItem(i).getUsername());
int section = list.size() - 1;
if (list.get(section) != null && !list.get(section).equals(letter)) {
list.add(letter);
section++;
positionOfSection.put(section, i);
}
sectionOfPosition.put(i, section);
}
return list.toArray(new String[list.size()]);
}
public SparseIntArray getEventCount(ArrayList<Integer> eventTypes) {
SparseIntArray returnArray = new SparseIntArray();
synchronized (_motionEvents) {
for (AdUnitMotionEvent currentEvent : _motionEvents) {
for (Integer currentType : eventTypes) {
if (currentEvent.getAction() == currentType) {
returnArray.put(currentType, returnArray.get(currentType, 0) + 1);
break;
}
}
}
}
return returnArray;
}
static int findFirstKeyLessThan(SparseIntArray cache, int position) {
int lo = 0;
int hi = cache.size() - 1;
while (lo <= hi) {
// Using unsigned shift here to divide by two because it is guaranteed to not
// overflow.
final int mid = (lo + hi) >>> 1;
final int midVal = cache.keyAt(mid);
if (midVal < position) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
int index = lo - 1;
if (index >= 0 && index < cache.size()) {
return cache.keyAt(index);
}
return -1;
}
/**
* @param mode Mode for the extractor. One of {@link #MODE_MULTI_PMT}, {@link #MODE_SINGLE_PMT}
* and {@link #MODE_HLS}.
* @param timestampAdjuster A timestamp adjuster for offsetting and scaling sample timestamps.
* @param payloadReaderFactory Factory for injecting a custom set of payload readers.
*/
public TsExtractor(
@Mode int mode,
TimestampAdjuster timestampAdjuster,
TsPayloadReader.Factory payloadReaderFactory) {
this.payloadReaderFactory = Assertions.checkNotNull(payloadReaderFactory);
this.mode = mode;
if (mode == MODE_SINGLE_PMT || mode == MODE_HLS) {
timestampAdjusters = Collections.singletonList(timestampAdjuster);
} else {
timestampAdjusters = new ArrayList<>();
timestampAdjusters.add(timestampAdjuster);
}
tsPacketBuffer = new ParsableByteArray(new byte[BUFFER_SIZE], 0);
trackIds = new SparseBooleanArray();
trackPids = new SparseBooleanArray();
tsPayloadReaders = new SparseArray<>();
continuityCounters = new SparseIntArray();
durationReader = new TsDurationReader();
pcrPid = -1;
resetPayloadReaders();
}
public void setSpecialInterval(JSONObject jsonObject) {
if (jsonObject != null) {
this.mSpecialInterval = new SparseIntArray();
Iterator<String> itr = jsonObject.keys();
while (itr.hasNext()) {
String key = itr.next();
try {
int index = Integer.parseInt(key);
int value = jsonObject.optInt(key);
if (value > 0) {
this.mSpecialInterval.put(index, value);
}
} catch (NumberFormatException e) {
}
}
}
}
@Before
public void setup() {
SparseIntArray buckets = new SparseIntArray();
for (int i = MIN_BUFFER_SIZE; i <= MAX_BUFFER_SIZE; i *= 2) {
buckets.put(i, 3);
}
mPool =
new FlexByteArrayPool(
mock(MemoryTrimmableRegistry.class),
new PoolParams(
Integer.MAX_VALUE,
Integer.MAX_VALUE,
buckets,
MIN_BUFFER_SIZE,
MAX_BUFFER_SIZE,
1));
mDelegatePool = mPool.mDelegatePool;
}
/**
* Called by CREATOR.
*
* @param in na
*/
public SavedStateScrolling(Parcel in) {
// Parcel 'in' has its parent(RecyclerView)'s saved state.
// To restore it, class loader that loaded RecyclerView is required.
Parcelable superState = in.readParcelable(RecyclerView.class.getClassLoader());
this.superState = superState != null ? superState : EMPTY_STATE;
prevFirstVisiblePosition = in.readInt();
prevFirstVisibleChildHeight = in.readInt();
prevScrolledChildrenHeight = in.readInt();
prevScrollY = in.readInt();
scrollY = in.readInt();
childrenHeights = new SparseIntArray();
final int numOfChildren = in.readInt();
if (0 < numOfChildren) {
for (int i = 0; i < numOfChildren; i++) {
final int key = in.readInt();
final int value = in.readInt();
childrenHeights.put(key, value);
}
}
}
protected int[] getTagDefinitionsForTagId(short tagId)
{
int[] ifds = IfdData.getIfds();
int[] defs = new int[ifds.length];
int counter = 0;
SparseIntArray infos = getTagInfo();
for (int i : ifds)
{
int def = defineTag(i, tagId);
if (infos.get(def) != DEFINITION_NULL)
{
defs[counter++] = def;
}
}
if (counter == 0)
{
return null;
}
return Arrays.copyOfRange(defs, 0, counter);
}
/**
* Returns if any of the children's {@link FlexItem#getOrder()} attributes are
* changed from the last measurement.
*
* @return {@code true} if changed from the last measurement, {@code false} otherwise.
*/
boolean isOrderChangedFromLastMeasurement(SparseIntArray orderCache) {
int childCount = mFlexContainer.getFlexItemCount();
if (orderCache.size() != childCount) {
return true;
}
for (int i = 0; i < childCount; i++) {
View view = mFlexContainer.getFlexItemAt(i);
if (view == null) {
continue;
}
FlexItem flexItem = (FlexItem) view.getLayoutParams();
if (flexItem.getOrder() != orderCache.get(i)) {
return true;
}
}
return false;
}
private void registerLevel(int level) {
LevelManager typesManager = mLevelManagerMap.get(level);
final SparseIntArray typeRes = typesManager.typeRes;
final int size = typeRes.size();
for (int i = 0; i < size; i++) {
final int type = typeRes.keyAt(i);
final int layoutResId = typeRes.valueAt(i);
if (layoutResId == 0) {
throw new RuntimeException(String.format(Locale.getDefault(), "are you sure register the layoutResId of level = %d?", type));
}
mLevelMap.put(type, level);
mLayoutMap.put(type, layoutResId);
}
mAttrMap.put(level, new AttrEntity(typesManager.minSize, typesManager.isFolded));
final int headerResId = typesManager.headerResId;
if (headerResId != 0) {
final int headerType = level - RecyclerViewAdapterHelper.HEADER_TYPE_DIFFER;
mLevelMap.put(headerType, level);
mLayoutMap.put(headerType, headerResId);
}
final int footerResId = typesManager.footerResId;
if (footerResId != 0) {
final int footerType = level - RecyclerViewAdapterHelper.FOOTER_TYPE_DIFFER;
mLevelMap.put(footerType, level);
mLayoutMap.put(footerType, footerResId);
}
}
@Override
protected SparseIntArray getLayoutIdMap() {
SparseIntArray sparseArray = new SparseIntArray();
sparseArray.put(ChatBean.TYPE_LEFT, R.layout.item_activity_chat_list_left);
sparseArray.put(ChatBean.TYPE_RIGHT, R.layout.item_activity_chat_list_right);
return sparseArray;
}
/**
* Set up pool params
* @param maxSizeSoftCap soft cap on max size of the pool
* @param maxSizeHardCap hard cap on max size of the pool
* @param bucketSizes (optional) bucket sizes and lengths for the pool
* @param minBucketSize min bucket size for the pool
* @param maxBucketSize max bucket size for the pool
*/
public PoolParams(
int maxSizeSoftCap,
int maxSizeHardCap,
@Nullable SparseIntArray bucketSizes,
int minBucketSize,
int maxBucketSize) {
Preconditions.checkState(maxSizeSoftCap >= 0 && maxSizeHardCap >= maxSizeSoftCap);
this.maxSizeSoftCap = maxSizeSoftCap;
this.maxSizeHardCap = maxSizeHardCap;
this.bucketSizes = bucketSizes;
this.minBucketSize = minBucketSize;
this.maxBucketSize = maxBucketSize;
}
@Override
protected SparseIntArray getLayoutIdMap() {
SparseIntArray sparseArray = new SparseIntArray();
sparseArray.put(TYPE_SEND_TEXT, R.layout.item_activity_chat_send);
sparseArray.put(TYPE_SEND_IMAGE, R.layout.item_activity_chat_send);
sparseArray.put(TYPE_SEND_VOICE, R.layout.item_activity_chat_send);
sparseArray.put(TYPE_SEND_LOCATION, R.layout.item_activity_chat_send);
sparseArray.put(TYPE_SEND_VIDEO, R.layout.item_activity_chat_send);
sparseArray.put(TYPE_RECEIVER_TEXT, R.layout.item_activity_chat_receive);
sparseArray.put(TYPE_RECEIVER_IMAGE, R.layout.item_activity_chat_receive);
sparseArray.put(TYPE_RECEIVER_LOCATION, R.layout.item_activity_chat_receive);
sparseArray.put(TYPE_RECEIVER_VOICE, R.layout.item_activity_chat_receive);
sparseArray.put(TYPE_RECEIVER_VIDEO, R.layout.item_activity_chat_receive);
return sparseArray;
}
/**
* @return table that maps SpeechRecognizer error codes to RecognizerIntent error codes
*/
public static SparseIntArray createErrorCodesServiceToIntent() {
SparseIntArray errorCodes = new SparseIntArray();
errorCodes.put(SpeechRecognizer.ERROR_AUDIO, RecognizerIntent.RESULT_AUDIO_ERROR);
errorCodes.put(SpeechRecognizer.ERROR_CLIENT, RecognizerIntent.RESULT_CLIENT_ERROR);
errorCodes.put(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS, RecognizerIntent.RESULT_CLIENT_ERROR);
errorCodes.put(SpeechRecognizer.ERROR_NETWORK, RecognizerIntent.RESULT_NETWORK_ERROR);
errorCodes.put(SpeechRecognizer.ERROR_NETWORK_TIMEOUT, RecognizerIntent.RESULT_NETWORK_ERROR);
errorCodes.put(SpeechRecognizer.ERROR_NO_MATCH, RecognizerIntent.RESULT_NO_MATCH);
errorCodes.put(SpeechRecognizer.ERROR_RECOGNIZER_BUSY, RecognizerIntent.RESULT_SERVER_ERROR);
errorCodes.put(SpeechRecognizer.ERROR_SERVER, RecognizerIntent.RESULT_SERVER_ERROR);
errorCodes.put(SpeechRecognizer.ERROR_SPEECH_TIMEOUT, RecognizerIntent.RESULT_NO_MATCH);
return errorCodes;
}
public UserPagerAdapter(Activity context, User user, FragmentManager fm) {
super(fm);
mActivity = context;
mUser = user;
mArray = new SparseIntArray(6);
mId = User.getUserId(mUser.path);
int key = 0;
if (user.getUpvoted() > 0) {
mArray.append(key, UPVOTED);
key++;
}
if (user.getCreated() > 0) {
mArray.append(key, CREATED);
key++;
}
if (user.getShowcased() > 0) {
mArray.append(key, SHOWCASED);
key++;
}
if (user.getCollections() > 0) {
mArray.append(key, COLLECTIONS);
key++;
}
if (user.getFollowers() > 0) {
mArray.append(key, FOLLOWERS);
key++;
}
if (user.getFollowing() > 0) {
mArray.append(key, FOLLOWING);
key++;
}
}
public void setEnabledPositionNoneOnNotifyDataSetChanged(boolean enabled) {
if (enabled) {
notifyNumberPool = new SparseIntArray();
notifyNumber = 0;
} else {
notifyNumberPool = null;
}
}
/**
* Default constructor
*
* @param sectionsAt and array with the positions of each section
*/
public SimpleSectionAdapter(int[] sectionsAt) {
positions = new SparseIntArray(sectionsAt.length);
Arrays.sort(sectionsAt);
for (int i : sectionsAt)
positions.put(i, positions.size());
}
protected int getTagDefinitionForTag(short tagId, short type, int count, int ifd) {
int[] defs = getTagDefinitionsForTagId(tagId);
if (defs == null) {
return TAG_NULL;
}
SparseIntArray infos = getTagInfo();
int ret = TAG_NULL;
for (int i : defs) {
int info = infos.get(i);
short def_type = getTypeFromInfo(info);
int def_count = getComponentCountFromInfo(info);
int[] def_ifds = getAllowedIfdsFromInfo(info);
boolean valid_ifd = false;
for (int j : def_ifds) {
if (j == ifd) {
valid_ifd = true;
break;
}
}
if (valid_ifd && type == def_type
&& (count == def_count || def_count == ExifTag.SIZE_UNDEFINED)) {
ret = i;
break;
}
}
return ret;
}
protected int getTagDefinitionForTag(short tagId, short type, int count, int ifd) {
int[] defs = getTagDefinitionsForTagId(tagId);
if (defs == null) {
return TAG_NULL;
}
SparseIntArray infos = getTagInfo();
int ret = TAG_NULL;
for (int i : defs) {
int info = infos.get(i);
short def_type = getTypeFromInfo(info);
int def_count = getComponentCountFromInfo(info);
int[] def_ifds = getAllowedIfdsFromInfo(info);
boolean valid_ifd = false;
for (int j : def_ifds) {
if (j == ifd) {
valid_ifd = true;
break;
}
}
if (valid_ifd && type == def_type
&& (count == def_count || def_count == ExifTag.SIZE_UNDEFINED)) {
ret = i;
break;
}
}
return ret;
}
@Override
protected SparseIntArray getLayoutIdMap() {
SparseIntArray sparseArray = new SparseIntArray();
sparseArray.put(SystemUtil.ImageItem.ITEM_CAMERA, R.layout.item_activity_photo_select_camera);
sparseArray.put(SystemUtil.ImageItem.ITEM_NORMAL, R.layout.item_activity_photo_select_normal);
return sparseArray;
}
private int findPointIndex(SparseIntArray points, int displayPosition) {
int index = points.indexOfKey(displayPosition);
if (index >= 0) {
// Exact match.
return index;
}
// One's complement gives index where the element would be inserted
// in sorted order.
index = ~index;
if (index > 0) {
return index - 1;
}
return -1;
}
private int findLeftLimit(SparseIntArray points, int end) {
int index = findPointIndex(points, end);
if (index >= 0) {
int limit = points.keyAt(index);
if (limit < end) {
return limit;
}
if (index > 0) {
return points.keyAt(index - 1);
}
}
return 0;
}
public static PoolParams get() {
SparseIntArray DEFAULT_BUCKETS = new SparseIntArray();
DEFAULT_BUCKETS.put(1 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(2 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(4 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(8 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(16 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(32 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(64 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(128 * ByteConstants.KB, SMALL_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(256 * ByteConstants.KB, LARGE_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(512 * ByteConstants.KB, LARGE_BUCKET_LENGTH);
DEFAULT_BUCKETS.put(1024 * ByteConstants.KB, LARGE_BUCKET_LENGTH);
return new PoolParams(getMaxSizeSoftCap(), getMaxSizeHardCap(), DEFAULT_BUCKETS);
}
private static boolean sparseIntArrayEquals(SparseIntArray a, SparseIntArray b) {
if (a == b) return true;
if (a == null) return b == null;
if (b == null) return false;
int size = a.size();
if (size != b.size()) return false;
for (int i=0; i<size; ++i) {
if (a.keyAt(i) != b.keyAt(i)) return false;
if (a.valueAt(i) != b.valueAt(i)) return false;
}
return true;
}
@Override
public void onCreate() {
super.onCreate();
//Add this first to avoid the runtime exceptions for the entire lifecycle of the service
setRouterServiceExceptionHandler();
//This must be done regardless of if this service shuts down or not
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
hasCalledStartForeground = false;
enterForeground("Waiting for connection...", FOREGROUND_TIMEOUT/1000, false);
hasCalledStartForeground = true;
resetForegroundTimeOut(FOREGROUND_TIMEOUT/1000);
}
if(!initCheck()){ // Run checks on process and permissions
deployNextRouterService();
closeSelf();
return;
}
initPassed = true;
synchronized(REGISTERED_APPS_LOCK){
registeredApps = new HashMap<String,RegisteredApp>();
}
closing = false;
synchronized(SESSION_LOCK){
this.bluetoothSessionMap = new SparseArray<String>();
this.sessionHashIdMap = new SparseIntArray();
this.cleanedSessionMap = new SparseIntArray();
}
packetExecutor = Executors.newSingleThreadExecutor();
startUpSequence();
}