下面列出了android.util.SparseIntArray#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Initialize the list of buckets. Get the bucket sizes (and bucket lengths) from the bucket
* sizes provider
* @param inUseCounts map of current buckets and their in use counts
*/
private synchronized void initBuckets(SparseIntArray inUseCounts) {
Preconditions.checkNotNull(inUseCounts);
// clear out all the buckets
mBuckets.clear();
// create the new buckets
final SparseIntArray bucketSizes = mPoolParams.bucketSizes;
if (bucketSizes != null) {
for (int i = 0; i < bucketSizes.size(); ++i) {
final int bucketSize = bucketSizes.keyAt(i);
final int maxLength = bucketSizes.valueAt(i);
int bucketInUseCount = inUseCounts.get(bucketSize, 0);
mBuckets.put(
bucketSize,
new Bucket<V>(
getSizeInBytes(bucketSize),
maxLength,
bucketInUseCount));
}
mAllowNewBuckets = false;
} else {
mAllowNewBuckets = true;
}
}
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 ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
ArrayList<AppOpsManager.OpEntry> resOps = null;
if (ops == null) {
resOps = new ArrayList<>();
for (int j=0; j<uidOps.size(); j++) {
resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
0, 0, 0, -1, null));
}
} else {
for (int j=0; j<ops.length; j++) {
int index = uidOps.indexOfKey(ops[j]);
if (index >= 0) {
if (resOps == null) {
resOps = new ArrayList<>();
}
resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
0, 0, 0, -1, null));
}
}
}
return resOps;
}
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;
}
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();
}
public @Nullable JSONObject toJSONObject() {
if (timeInStateS.length == 0) {
return null;
}
// This is slightly more complex than simply using a hashmap to aggregate frequencies
// because SparseIntArray doesn't override equals/hash correctly.
// Implemented in a fairly expensive, n^2 way because number of cores is presumably
// very low.
boolean[] isHandled = new boolean[timeInStateS.length];
JSONObject output = new JSONObject();
for (int i = 0, cores = timeInStateS.length; i < cores; i++) {
SparseIntArray current = timeInStateS[i];
if (current.size() == 0 || isHandled[i]) {
continue;
}
int cpumask = 1 << i;
for (int j = i + 1; j < cores; j++) {
if (CpuFrequencyMetrics.sparseIntArrayEquals(current, timeInStateS[j])) {
cpumask |= 1 << j;
isHandled[j] = true;
}
}
try {
output.put(Integer.toHexString(cpumask), convert(current));
} catch (JSONException je) {
SystemMetricsLogger.wtf("CpuFrequencyMetricsReporter", "Unable to store event", je);
}
}
return output;
}
private static Pair[] toPairArray(SparseIntArray counts) {
final int s = counts.size();
Pair[] pairs = new Pair[s];
for (int i = 0; i < s; i++) {
Pair p = new Pair();
p.key = counts.keyAt(i);
p.value = counts.valueAt(i);
pairs[i] = p;
}
return pairs;
}
private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
pw.print("UID firewall ");
pw.print(name);
pw.print(" rule: [");
final int size = rules.size();
for (int i = 0; i < size; i++) {
pw.print(rules.keyAt(i));
pw.print(":");
pw.print(rules.valueAt(i));
if (i < size - 1) pw.print(",");
}
pw.println("]");
}
private int findRightLimit(SparseIntArray points, int start) {
int index = findPointIndex(points, start) + 1;
if (index >= points.size()) {
return mTranslation.getCells().length;
}
return points.keyAt(index);
}
/**
* @hide
*/
public final void writeSparseIntArray(SparseIntArray val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
writeInt(N);
int i=0;
while (i < N) {
writeInt(val.keyAt(i));
writeInt(val.valueAt(i));
i++;
}
}
/**
* Dump per uid binder proxy counts to the logcat.
*/
private void dumpPerUidProxyCounts() {
SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
if (counts.size() == 0) return;
Log.d(Binder.TAG, "Per Uid Binder Proxy Counts:");
for (int i = 0; i < counts.size(); i++) {
final int uid = counts.keyAt(i);
final int binderCount = counts.valueAt(i);
Log.d(Binder.TAG, "UID : " + uid + " count = " + binderCount);
}
}
/**
* Creates a new instance of the NativeMemoryChunkPool class
* @param memoryTrimmableRegistry the memory manager to register with
* @param poolParams provider for pool parameters
* @param nativeMemoryChunkPoolStatsTracker
*/
public NativeMemoryChunkPool(
MemoryTrimmableRegistry memoryTrimmableRegistry,
PoolParams poolParams,
PoolStatsTracker nativeMemoryChunkPoolStatsTracker) {
super(memoryTrimmableRegistry, poolParams, nativeMemoryChunkPoolStatsTracker);
SparseIntArray bucketSizes = poolParams.bucketSizes;
mBucketSizes = new int[bucketSizes.size()];
for (int i = 0; i < mBucketSizes.length; ++i) {
mBucketSizes[i] = bucketSizes.keyAt(i);
}
initialize();
}
/**
* Initialize a new instance of the MemoryChunkPool
*
* @param memoryTrimmableRegistry the memory manager to register with
* @param poolParams provider for pool parameters
* @param memoryChunkPoolStatsTracker the pool stats tracker
*/
MemoryChunkPool(
MemoryTrimmableRegistry memoryTrimmableRegistry,
PoolParams poolParams,
PoolStatsTracker memoryChunkPoolStatsTracker) {
super(memoryTrimmableRegistry, poolParams, memoryChunkPoolStatsTracker);
SparseIntArray bucketSizes = poolParams.bucketSizes;
mBucketSizes = new int[bucketSizes.size()];
for (int i = 0; i < mBucketSizes.length; ++i) {
mBucketSizes[i] = bucketSizes.keyAt(i);
}
initialize();
}
/**
* Initialize the list of buckets. Get the bucket sizes (and bucket lengths) from the bucket sizes
* provider
*
* @param inUseCounts map of current buckets and their in use counts
*/
private synchronized void legacyInitBuckets(SparseIntArray inUseCounts) {
Preconditions.checkNotNull(inUseCounts);
// clear out all the buckets
mBuckets.clear();
// create the new buckets
final SparseIntArray bucketSizes = mPoolParams.bucketSizes;
if (bucketSizes != null) {
for (int i = 0; i < bucketSizes.size(); ++i) {
final int bucketSize = bucketSizes.keyAt(i);
final int maxLength = bucketSizes.valueAt(i);
int bucketInUseCount = inUseCounts.get(bucketSize, 0);
mBuckets.put(
bucketSize,
new Bucket<V>(
getSizeInBytes(bucketSize),
maxLength,
bucketInUseCount,
mPoolParams.fixBucketsReinitialization));
}
mAllowNewBuckets = false;
} else {
mAllowNewBuckets = true;
}
}
public static final IntArrayList valuesToList(final SparseIntArray pSparseIntArray) {
final int size = pSparseIntArray.size();
final IntArrayList result = new IntArrayList(size);
for (int i = 0; i < size; i++) {
result.add(pSparseIntArray.valueAt(i));
}
return result;
}
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);
}
}
public static void writeSparseIntArray(Parcel out, SparseIntArray value) {
if (value == null) {
out.writeInt(-1);
} else {
int count = value.size();
out.writeInt(count);
for (int i = 0; i < count; ++i) {
out.writeInt(value.keyAt(i));
out.writeInt(value.valueAt(i));
}
}
}
/**
* Handles restoring an individual tab.
*
* @param tabToRestore Meta data about the tab to be restored.
* @param tabState The previously serialized state of the tab to be restored.
* @param setAsActive Whether the tab should be set as the active tab as part of the
* restoration process.
*/
@VisibleForTesting
protected void restoreTab(
TabRestoreDetails tabToRestore, TabState tabState, boolean setAsActive) {
// If we don't have enough information about the Tab, bail out.
boolean isIncognito = isIncognitoTabBeingRestored(tabToRestore, tabState);
if (tabState == null) {
if (tabToRestore.isIncognito == null) {
Log.w(TAG, "Failed to restore tab: not enough info about its type was available.");
return;
} else if (isIncognito) {
Log.i(TAG, "Failed to restore Incognito tab: its TabState could not be restored.");
return;
}
}
TabModel model = mTabModelSelector.getModel(isIncognito);
SparseIntArray restoredTabs = isIncognito ? mIncognitoTabsRestored : mNormalTabsRestored;
int restoredIndex = 0;
if (tabToRestore.fromMerge) {
// Put any tabs being merged into this list at the end.
restoredIndex = mTabModelSelector.getModel(isIncognito).getCount();
} else if (restoredTabs.size() > 0
&& tabToRestore.originalIndex > restoredTabs.keyAt(restoredTabs.size() - 1)) {
// If the tab's index is too large, restore it at the end of the list.
restoredIndex = restoredTabs.size();
} else {
// Otherwise try to find the tab we should restore before, if any.
for (int i = 0; i < restoredTabs.size(); i++) {
if (restoredTabs.keyAt(i) > tabToRestore.originalIndex) {
Tab nextTabByIndex = TabModelUtils.getTabById(model, restoredTabs.valueAt(i));
restoredIndex = nextTabByIndex != null ? model.indexOf(nextTabByIndex) : -1;
break;
}
}
}
int tabId = tabToRestore.id;
if (tabState != null) {
mTabCreatorManager.getTabCreator(isIncognito).createFrozenTab(
tabState, tabToRestore.id, restoredIndex);
} else {
if (NewTabPage.isNTPUrl(tabToRestore.url) && !setAsActive && !tabToRestore.fromMerge) {
Log.i(TAG, "Skipping restore of non-selected NTP.");
return;
}
Log.w(TAG, "Failed to restore TabState; creating Tab with last known URL.");
Tab fallbackTab = mTabCreatorManager.getTabCreator(isIncognito).createNewTab(
new LoadUrlParams(tabToRestore.url), TabModel.TabLaunchType.FROM_RESTORE, null);
tabId = fallbackTab.getId();
model.moveTab(tabId, restoredIndex);
}
// If the tab is being restored from a merge and its index is 0, then the model being
// merged into doesn't contain any tabs. Select the first tab to avoid having no tab
// selected. TODO(twellington): The first tab will always be selected. Instead, the tab that
// was selected in the other model before the merge should be selected after the merge.
if (setAsActive || (tabToRestore.fromMerge && restoredIndex == 0)) {
boolean wasIncognitoTabModelSelected = mTabModelSelector.isIncognitoSelected();
int selectedModelTabCount = mTabModelSelector.getCurrentModel().getCount();
TabModelUtils.setIndex(model, TabModelUtils.getTabIndexById(model, tabId));
boolean isIncognitoTabModelSelected = mTabModelSelector.isIncognitoSelected();
// Setting the index will cause the tab's model to be selected. Set it back to the model
// that was selected before setting the index if the index is being set during a merge
// unless the previously selected model is empty (e.g. showing the empty background
// view on tablets).
if (tabToRestore.fromMerge
&& wasIncognitoTabModelSelected != isIncognitoTabModelSelected
&& selectedModelTabCount != 0) {
mTabModelSelector.selectModel(wasIncognitoTabModelSelected);
}
}
restoredTabs.put(tabToRestore.originalIndex, tabId);
}
public static boolean isEmpty(final SparseIntArray obj) {
return obj == null || obj.size() == 0;
}
private static void copyArrayInto(SparseIntArray source, SparseIntArray destination) {
destination.clear();
for (int i = 0; i < source.size(); i++) {
destination.append(source.keyAt(i), source.valueAt(i));
}
}