下面列出了怎么用android.util.Pair的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Get all data from this host.
*/
public List<Pair<String, String>> getAll() {
List<Pair<String, String>> result = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + ";", null);
try {
while (cursor.moveToNext()) {
String host = SqlUtils.getString(cursor, COLUMN_HOST, null);
String ip = SqlUtils.getString(cursor, COLUMN_IP, null);
InetAddress inetAddress = toInetAddress(host, ip);
if (inetAddress == null) {
continue;
}
result.add(new Pair<>(host, ip));
}
} finally {
cursor.close();
}
return result;
}
/**
* Handle {@link android.content.pm.ShortcutManager#createShortcutResultIntent(ShortcutInfo)}.
* In this flow the PinItemRequest is delivered to the caller app. Its the app's responsibility
* to send it to the Launcher app (via {@link android.app.Activity#setResult(int, Intent)}).
*/
public Intent createShortcutResultIntent(@NonNull ShortcutInfo inShortcut, int userId) {
// Find the default launcher activity
final int launcherUserId = mService.getParentOrSelfUserId(userId);
final ComponentName defaultLauncher = mService.getDefaultLauncher(launcherUserId);
if (defaultLauncher == null) {
Log.e(TAG, "Default launcher not found.");
return null;
}
// Make sure the launcher user is unlocked. (it's always the parent profile, so should
// really be unlocked here though.)
mService.throwIfUserLockedL(launcherUserId);
// Next, validate the incoming shortcut, etc.
final PinItemRequest request = requestPinShortcutLocked(inShortcut, null,
Pair.create(defaultLauncher, launcherUserId));
return new Intent().putExtra(LauncherApps.EXTRA_PIN_ITEM_REQUEST, request);
}
@Override
public Bundle getCache(String packageName, Uri key, int userId) {
enforceCrossUserPermission(userId, TAG);
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CACHE_CONTENT, TAG);
mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
packageName);
final String providerPackageName = getProviderPackageName(key);
final Pair<String, Uri> fullKey = Pair.create(packageName, key);
synchronized (mCache) {
final ArrayMap<Pair<String, Uri>, Bundle> cache = findOrCreateCacheLocked(userId,
providerPackageName);
return cache.get(fullKey);
}
}
/**
* Create a new JobStatus that was loaded from disk. We ignore the provided
* {@link android.app.job.JobInfo} time criteria because we can load a persisted periodic job
* from the {@link com.android.server.job.JobStore} and still want to respect its
* wallclock runtime rather than resetting it on every boot.
* We consider a freshly loaded job to no longer be in back-off, and the associated
* standby bucket is whatever the OS thinks it should be at this moment.
*/
public JobStatus(JobInfo job, int callingUid, String sourcePkgName, int sourceUserId,
int standbyBucket, long baseHeartbeat, String sourceTag,
long earliestRunTimeElapsedMillis, long latestRunTimeElapsedMillis,
long lastSuccessfulRunTime, long lastFailedRunTime,
Pair<Long, Long> persistedExecutionTimesUTC,
int innerFlags) {
this(job, callingUid, resolveTargetSdkVersion(job), sourcePkgName, sourceUserId,
standbyBucket, baseHeartbeat,
sourceTag, 0,
earliestRunTimeElapsedMillis, latestRunTimeElapsedMillis,
lastSuccessfulRunTime, lastFailedRunTime, innerFlags);
// Only during initial inflation do we record the UTC-timebase execution bounds
// read from the persistent store. If we ever have to recreate the JobStatus on
// the fly, it means we're rescheduling the job; and this means that the calculated
// elapsed timebase bounds intrinsically become correct.
this.mPersistedUtcTimes = persistedExecutionTimesUTC;
if (persistedExecutionTimesUTC != null) {
if (DEBUG) {
Slog.i(TAG, "+ restored job with RTC times because of bad boot clock");
}
}
}
@Override
public void draw(final int texName, final GlFramebufferObject fbo) {
prevTexName = texName;
for (final Pair<GlFilter, GlFramebufferObject> pair : list) {
if (pair.second != null) {
if (pair.first != null) {
pair.second.enable();
GLES20.glClear(GL_COLOR_BUFFER_BIT);
pair.first.draw(prevTexName, pair.second);
}
prevTexName = pair.second.getTexName();
} else {
if (fbo != null) {
fbo.enable();
} else {
GLES20.glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
if (pair.first != null) {
pair.first.draw(prevTexName, fbo);
}
}
}
}
protected void onMainActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SignInController.RC_SIGN_IN) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
signInController.onSignInActivityResult(googleSignInResult);
} else if (requestCode == AchievementsController.RC_ACHIEVEMENT_UI || requestCode == LeaderboardsController.RC_LEADERBOARD_UI) {
Pair<Boolean, String> isConnected = connectionController.isConnected();
godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.PLAYER_CONNECTED, new Object[]{isConnected.first, isConnected.second});
} else if (requestCode == SavedGamesController.RC_SAVED_GAMES) {
if (data != null) {
if (data.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA)) {
SnapshotMetadata snapshotMetadata = data.getParcelableExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA);
if (snapshotMetadata != null) {
savedGamesController.loadSnapshot(snapshotMetadata.getUniqueName());
}
} else if (data.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_NEW)) {
String unique = new BigInteger(281, new Random()).toString(13);
String currentSaveName = appActivity.getString(R.string.default_game_name) + unique;
savedGamesController.createNewSnapshot(currentSaveName);
}
}
}
}
/**
* Queries the cache to obtain the request length and the number of bytes already cached for a
* given {@link DataSpec}.
*
* @param dataSpec Defines the data to be checked.
* @param cache A {@link Cache} which has the data.
* @param cacheKeyFactory An optional factory for cache keys.
* @return A pair containing the request length and the number of bytes that are already cached.
*/
public static Pair<Long, Long> getCached(
DataSpec dataSpec, Cache cache, @Nullable CacheKeyFactory cacheKeyFactory) {
String key = buildCacheKey(dataSpec, cacheKeyFactory);
long position = dataSpec.absoluteStreamPosition;
long requestLength = getRequestLength(dataSpec, cache, key);
long bytesAlreadyCached = 0;
long bytesLeft = requestLength;
while (bytesLeft != 0) {
long blockLength =
cache.getCachedLength(
key, position, bytesLeft != C.LENGTH_UNSET ? bytesLeft : Long.MAX_VALUE);
if (blockLength > 0) {
bytesAlreadyCached += blockLength;
} else {
blockLength = -blockLength;
if (blockLength == Long.MAX_VALUE) {
break;
}
}
position += blockLength;
bytesLeft -= bytesLeft == C.LENGTH_UNSET ? 0 : blockLength;
}
return Pair.create(requestLength, bytesAlreadyCached);
}
private static void processSticker(@NonNull Context context, @NonNull AttachmentSecret attachmentSecret, @NonNull SQLiteDatabase db, @NonNull Sticker sticker, BackupRecordInputStream inputStream)
throws IOException
{
File stickerDirectory = context.getDir(AttachmentDatabase.DIRECTORY, Context.MODE_PRIVATE);
File dataFile = File.createTempFile("sticker", ".mms", stickerDirectory);
Pair<byte[], OutputStream> output = ModernEncryptingPartOutputStream.createFor(attachmentSecret, dataFile, false);
inputStream.readAttachmentTo(output.second, sticker.getLength());
ContentValues contentValues = new ContentValues();
contentValues.put(StickerDatabase.FILE_PATH, dataFile.getAbsolutePath());
contentValues.put(StickerDatabase.FILE_LENGTH, sticker.getLength());
contentValues.put(StickerDatabase.FILE_RANDOM, output.first);
db.update(StickerDatabase.TABLE_NAME, contentValues,
StickerDatabase._ID + " = ?",
new String[] {String.valueOf(sticker.getRowId())});
}
private void initViewData(View v) {
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(new RecyclerView.Adapter<ResultItemViewHolder>() {
private LayoutInflater mInflater = LayoutInflater.from(ReplayMainResultFragment.this.getActivity());
@Override
public ResultItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ResultItemViewHolder(mInflater.inflate(R.layout.item_case_result, parent, false));
}
@Override
public void onBindViewHolder(ResultItemViewHolder holder, int position) {
Pair<String, String> data = contents.get(position);
holder.bindData(data.first, data.second);
}
@Override
public int getItemCount() {
return contents == null? 0: contents.size();
}
});
recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(),
LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.divider_color)));
}
private void updateGroupReceiptStatus(@NonNull SentTranscriptMessage message, long messageId, @NonNull GroupId groupString) {
GroupReceiptDatabase receiptDatabase = DatabaseFactory.getGroupReceiptDatabase(context);
List<Recipient> messageRecipients = Stream.of(message.getRecipients()).map(address -> Recipient.externalPush(context, address)).toList();
List<Recipient> members = DatabaseFactory.getGroupDatabase(context).getGroupMembers(groupString, GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
Map<RecipientId, Integer> localReceipts = Stream.of(receiptDatabase.getGroupReceiptInfo(messageId))
.collect(Collectors.toMap(GroupReceiptInfo::getRecipientId, GroupReceiptInfo::getStatus));
for (Recipient messageRecipient : messageRecipients) {
//noinspection ConstantConditions
if (localReceipts.containsKey(messageRecipient.getId()) && localReceipts.get(messageRecipient.getId()) < GroupReceiptDatabase.STATUS_UNDELIVERED) {
receiptDatabase.update(messageRecipient.getId(), messageId, GroupReceiptDatabase.STATUS_UNDELIVERED, message.getTimestamp());
} else if (!localReceipts.containsKey(messageRecipient.getId())) {
receiptDatabase.insert(Collections.singletonList(messageRecipient.getId()), messageId, GroupReceiptDatabase.STATUS_UNDELIVERED, message.getTimestamp());
}
}
List<org.whispersystems.libsignal.util.Pair<RecipientId, Boolean>> unidentifiedStatus = Stream.of(members)
.map(m -> new org.whispersystems.libsignal.util.Pair<>(m.getId(), message.isUnidentified(m.requireServiceId())))
.toList();
receiptDatabase.setUnidentified(unidentifiedStatus, messageId);
}
public static AsyncSSLServerSocket listenSecure(final Context context, final AsyncServer server, final String subjectName, final InetAddress host, final int port, final ListenCallback handler) {
final ObjectHolder<AsyncSSLServerSocket> holder = new ObjectHolder<>();
server.run(() -> {
try {
Pair<KeyPair, Certificate> keyCert = selfSignCertificate(context, subjectName);
KeyPair pair = keyCert.first;
Certificate cert = keyCert.second;
holder.held = listenSecure(server, pair.getPrivate(), cert, host, port, handler);
}
catch (Exception e) {
handler.onCompleted(e);
}
});
return holder.held;
}
protected void cutSpiral(int position) {
StraightArea area = areas.get(position);
areas.remove(area);
Pair<List<StraightLine>, List<StraightArea>> spilt = cutAreaSpiral(area);
lines.addAll(spilt.first);
areas.addAll(spilt.second);
updateLineLimit();
sortAreas();
Step step = new Step();
step.type = Step.CUT_SPIRAL;
step.position = position;
steps.add(step);
}
/**
* Called to alert the {@link CaptureCollector} that the jpeg capture has completed.
*
* @return a pair containing the {@link RequestHolder} and the timestamp of the capture.
*/
public Pair<RequestHolder, Long> jpegProduced() {
final ReentrantLock lock = this.mLock;
lock.lock();
try {
CaptureHolder h = mJpegProduceQueue.poll();
if (h == null) {
Log.w(TAG, "jpegProduced called with no jpeg request on queue!");
return null;
}
h.setJpegProduced();
return new Pair<>(h.mRequest, h.mTimestamp);
} finally {
lock.unlock();
}
}
/**
* Returns list of all grants as {@link Pair pairs} of account name and UID.
*/
List<Pair<String, Integer>> findAllAccountGrants() {
SQLiteDatabase db = mDeDatabase.getReadableDatabase();
try (Cursor cursor = db.rawQuery(ACCOUNT_ACCESS_GRANTS, null)) {
if (cursor == null || !cursor.moveToFirst()) {
return Collections.emptyList();
}
List<Pair<String, Integer>> results = new ArrayList<>();
do {
final String accountName = cursor.getString(0);
final int uid = cursor.getInt(1);
results.add(Pair.create(accountName, uid));
} while (cursor.moveToNext());
return results;
}
}
/**
* Parses the edts atom (defined in 14496-12 subsection 8.6.5).
*
* @param edtsAtom edts (edit box) atom to decode.
* @return Pair of edit list durations and edit list media times, or a pair of nulls if they are
* not present.
*/
private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom edtsAtom) {
Atom.LeafAtom elst;
if (edtsAtom == null || (elst = edtsAtom.getLeafAtomOfType(Atom.TYPE_elst)) == null) {
return Pair.create(null, null);
}
ParsableByteArray elstData = elst.data;
elstData.setPosition(Atom.HEADER_SIZE);
int fullAtom = elstData.readInt();
int version = Atom.parseFullAtomVersion(fullAtom);
int entryCount = elstData.readUnsignedIntToInt();
long[] editListDurations = new long[entryCount];
long[] editListMediaTimes = new long[entryCount];
for (int i = 0; i < entryCount; i++) {
editListDurations[i] =
version == 1 ? elstData.readUnsignedLongToLong() : elstData.readUnsignedInt();
editListMediaTimes[i] = version == 1 ? elstData.readLong() : elstData.readInt();
int mediaRateInteger = elstData.readShort();
if (mediaRateInteger != 1) {
// The extractor does not handle dwell edits (mediaRateInteger == 0).
throw new IllegalArgumentException("Unsupported media rate.");
}
elstData.skipBytes(2);
}
return Pair.create(editListDurations, editListMediaTimes);
}
/**
* Parses encryption data from an audio/video sample entry, returning a pair consisting of the
* unencrypted atom type and a {@link TrackEncryptionBox}. Null is returned if no common
* encryption sinf atom was present.
*/
private static Pair<Integer, TrackEncryptionBox> parseSampleEntryEncryptionData(
ParsableByteArray parent, int position, int size) {
int childPosition = parent.getPosition();
while (childPosition - position < size) {
parent.setPosition(childPosition);
int childAtomSize = parent.readInt();
Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive");
int childAtomType = parent.readInt();
if (childAtomType == Atom.TYPE_sinf) {
Pair<Integer, TrackEncryptionBox> result = parseCommonEncryptionSinfFromParent(parent,
childPosition, childAtomSize);
if (result != null) {
return result;
}
}
childPosition += childAtomSize;
}
return null;
}
@Override
public void handleMessage(Message msg) {
final int action = msg.what;
switch (action) {
case MSG_SEND_LIST:
final Pair<RemoteCallback, List<CacheQuotaHint>> pair =
(Pair<RemoteCallback, List<CacheQuotaHint>>) msg.obj;
List<CacheQuotaHint> processed = onComputeCacheQuotaHints(pair.second);
final Bundle data = new Bundle();
data.putParcelableList(REQUEST_LIST_KEY, processed);
final RemoteCallback callback = pair.first;
callback.sendResult(data);
break;
default:
Log.w(TAG, "Handling unknown message: " + action);
}
}
/**
* Given a set of reference points as coordinates in {@code xReferences} and {@code yReferences}
* and an x-axis value, linearly interpolates between corresponding reference points to give a
* y-axis value.
*
* @param x The x-axis value for which a y-axis value is needed.
* @param xReferences x coordinates of reference points.
* @param yReferences y coordinates of reference points.
* @return The linearly interpolated y-axis value.
*/
private static Pair<Long, Long> linearlyInterpolate(
long x, long[] xReferences, long[] yReferences) {
int previousReferenceIndex =
Util.binarySearchFloor(xReferences, x, /* inclusive= */ true, /* stayInBounds= */ true);
long xPreviousReference = xReferences[previousReferenceIndex];
long yPreviousReference = yReferences[previousReferenceIndex];
int nextReferenceIndex = previousReferenceIndex + 1;
if (nextReferenceIndex == xReferences.length) {
return Pair.create(xPreviousReference, yPreviousReference);
} else {
long xNextReference = xReferences[nextReferenceIndex];
long yNextReference = yReferences[nextReferenceIndex];
double proportion =
xNextReference == xPreviousReference
? 0.0
: ((double) x - xPreviousReference) / (xNextReference - xPreviousReference);
long y = (long) (proportion * (yNextReference - yPreviousReference)) + yPreviousReference;
return Pair.create(x, y);
}
}
private void maybeUpdateVideoFormat(EventTime eventTime, @Nullable Format newFormat) {
if (Util.areEqual(currentVideoFormat, newFormat)) {
return;
}
maybeRecordVideoFormatTime(eventTime.realtimeMs);
if (newFormat != null) {
if (initialVideoFormatHeight == C.LENGTH_UNSET && newFormat.height != Format.NO_VALUE) {
initialVideoFormatHeight = newFormat.height;
}
if (initialVideoFormatBitrate == C.LENGTH_UNSET && newFormat.bitrate != Format.NO_VALUE) {
initialVideoFormatBitrate = newFormat.bitrate;
}
}
currentVideoFormat = newFormat;
if (keepHistory) {
videoFormatHistory.add(Pair.create(eventTime, currentVideoFormat));
}
}
private ArrayMap<Pair<String, Uri>, Bundle> findOrCreateCacheLocked(int userId,
String providerPackageName) {
ArrayMap<String, ArrayMap<Pair<String, Uri>, Bundle>> userCache = mCache.get(userId);
if (userCache == null) {
userCache = new ArrayMap<>();
mCache.put(userId, userCache);
}
ArrayMap<Pair<String, Uri>, Bundle> packageCache = userCache.get(providerPackageName);
if (packageCache == null) {
packageCache = new ArrayMap<>();
userCache.put(providerPackageName, packageCache);
}
return packageCache;
}
private static Pair<String, ? extends AlgorithmParameterSpec>
getSignatureAlgorithmJcaSignatureAlgorithm(int sigAlgorithm) {
switch (sigAlgorithm) {
case SIGNATURE_RSA_PSS_WITH_SHA256:
return Pair.create(
"SHA256withRSA/PSS",
new PSSParameterSpec(
"SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 256 / 8, 1));
case SIGNATURE_RSA_PSS_WITH_SHA512:
return Pair.create(
"SHA512withRSA/PSS",
new PSSParameterSpec(
"SHA-512", "MGF1", MGF1ParameterSpec.SHA512, 512 / 8, 1));
case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256:
return Pair.create("SHA256withRSA", null);
case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512:
return Pair.create("SHA512withRSA", null);
case SIGNATURE_ECDSA_WITH_SHA256:
return Pair.create("SHA256withECDSA", null);
case SIGNATURE_ECDSA_WITH_SHA512:
return Pair.create("SHA512withECDSA", null);
case SIGNATURE_DSA_WITH_SHA256:
return Pair.create("SHA256withDSA", null);
default:
throw new IllegalArgumentException(
"Unknown signature algorithm: 0x"
+ Long.toHexString(sigAlgorithm & 0xffffffff));
}
}
/**
* Adjusts the alarm delivery time based on the current app standby bucket.
* @param alarm The alarm to adjust
* @return true if the alarm delivery time was updated.
*/
private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
if (isExemptFromAppStandby(alarm)) {
return false;
}
if (mAppStandbyParole) {
if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
// We did defer this alarm earlier, restore original requirements
alarm.whenElapsed = alarm.expectedWhenElapsed;
alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
return true;
}
return false;
}
final long oldWhenElapsed = alarm.whenElapsed;
final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
final String sourcePackage = alarm.sourcePackage;
final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
if (lastElapsed > 0) {
final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
if (alarm.expectedWhenElapsed < minElapsed) {
alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
} else {
// app is now eligible to run alarms at the originally requested window.
// Restore original requirements in case they were changed earlier.
alarm.whenElapsed = alarm.expectedWhenElapsed;
alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
}
}
return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
}
private static void increaseLogCount(HashMap<String, Pair<Long, Integer>> cache,
String message) {
Pair<Long, Integer> timing = cache.get(message);
if (timing != null) {
cache.put(message, new Pair<>(timing.first, timing.second + 1));
}
}
private boolean isAdapterDelayed(EndPoint target) {
long now = SystemClock.elapsedRealtime();
Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(target);
if (backoff != null && backoff.first != SyncStorageEngine.NOT_IN_BACKOFF_MODE
&& backoff.first > now) {
return true;
}
if (mSyncStorageEngine.getDelayUntilTime(target) > now) {
return true;
}
return false;
}
static Pair<String, ? extends AlgorithmParameterSpec>
getSignatureAlgorithmJcaSignatureAlgorithm(int sigAlgorithm) {
switch (sigAlgorithm) {
case SIGNATURE_RSA_PSS_WITH_SHA256:
return Pair.create(
"SHA256withRSA/PSS",
new PSSParameterSpec(
"SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 256 / 8, 1));
case SIGNATURE_RSA_PSS_WITH_SHA512:
return Pair.create(
"SHA512withRSA/PSS",
new PSSParameterSpec(
"SHA-512", "MGF1", MGF1ParameterSpec.SHA512, 512 / 8, 1));
case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256:
case SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256:
return Pair.create("SHA256withRSA", null);
case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512:
return Pair.create("SHA512withRSA", null);
case SIGNATURE_ECDSA_WITH_SHA256:
case SIGNATURE_VERITY_ECDSA_WITH_SHA256:
return Pair.create("SHA256withECDSA", null);
case SIGNATURE_ECDSA_WITH_SHA512:
return Pair.create("SHA512withECDSA", null);
case SIGNATURE_DSA_WITH_SHA256:
case SIGNATURE_VERITY_DSA_WITH_SHA256:
return Pair.create("SHA256withDSA", null);
default:
throw new IllegalArgumentException(
"Unknown signature algorithm: 0x"
+ Long.toHexString(sigAlgorithm & 0xffffffff));
}
}
/**
* Extract a job's earliest/latest run time data from XML. These are returned in
* unadjusted UTC wall clock time, because we do not yet know whether the system
* clock is reliable for purposes of calculating deltas from 'now'.
*
* @param parser
* @return A Pair of timestamps in UTC wall-clock time. The first is the earliest
* time at which the job is to become runnable, and the second is the deadline at
* which it becomes overdue to execute.
* @throws NumberFormatException
*/
private Pair<Long, Long> buildRtcExecutionTimesFromXml(XmlPullParser parser)
throws NumberFormatException {
String val;
// Pull out execution time data.
val = parser.getAttributeValue(null, "delay");
final long earliestRunTimeRtc = (val != null)
? Long.parseLong(val)
: JobStatus.NO_EARLIEST_RUNTIME;
val = parser.getAttributeValue(null, "deadline");
final long latestRunTimeRtc = (val != null)
? Long.parseLong(val)
: JobStatus.NO_LATEST_RUNTIME;
return Pair.create(earliestRunTimeRtc, latestRunTimeRtc);
}
void dispatchOnFragmentViewCreated(Fragment f, View v, Bundle savedInstanceState,
boolean onlyRecursive) {
if (mParent != null) {
FragmentManager parentManager = mParent.getFragmentManager();
if (parentManager instanceof FragmentManagerImpl) {
((FragmentManagerImpl) parentManager)
.dispatchOnFragmentViewCreated(f, v, savedInstanceState, true);
}
}
for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) {
if (!onlyRecursive || p.second) {
p.first.onFragmentViewCreated(this, f, v, savedInstanceState);
}
}
}
private @NonNull Pair<String, Integer> getVibrateSummary(@NonNull Context context, @NonNull VibrateState vibrateState) {
if (vibrateState == VibrateState.DEFAULT) {
return new Pair<>(context.getString(R.string.preferences__default), 0);
} else if (vibrateState == VibrateState.ENABLED) {
return new Pair<>(context.getString(R.string.RecipientPreferenceActivity_enabled), 1);
} else {
return new Pair<>(context.getString(R.string.RecipientPreferenceActivity_disabled), 2);
}
}
public void handleCheckKeepalivesStillValid(NetworkAgentInfo nai) {
HashMap <Integer, KeepaliveInfo> networkKeepalives = mKeepalives.get(nai);
if (networkKeepalives != null) {
ArrayList<Pair<Integer, Integer>> invalidKeepalives = new ArrayList<>();
for (int slot : networkKeepalives.keySet()) {
int error = networkKeepalives.get(slot).isValid();
if (error != SUCCESS) {
invalidKeepalives.add(Pair.create(slot, error));
}
}
for (Pair<Integer, Integer> slotAndError: invalidKeepalives) {
handleStopKeepalive(nai, slotAndError.first, slotAndError.second);
}
}
}
private void inflateAddresses() {
for (Pair<Integer, String[]> pair : contact.getAddressList()) {
final View layout = layoutInflater.inflate(R.layout.contact_address, ll, false);
final TextView tv_addressType = layout.findViewById(R.id.tv_address);
final BaldPictureTextButton button = layout.findViewById(R.id.address_button);
tv_addressType.setText(
String.format("%s %s",
String.valueOf(ContactsContract.CommonDataKinds.SipAddress.getTypeLabel(getResources(),
pair.first,
getText(R.string.custom)))
, String.valueOf(getText(R.string.address)
)
)
);
final StringBuilder stringBuilder = new StringBuilder();
for (final String s : pair.second) {
if (s == null || s.equals(""))
continue;
stringBuilder.append(s).append(" ");
}
button.setText(stringBuilder);
button.setOnClickListener(v -> startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + stringBuilder))));
ll.addView(layout);
}
}