下面列出了怎么用android.annotation.NonNull的API类实例代码及写法,或者点击链接到github查看源代码。
private void addUninstalledInstantAppLPw(@NonNull PackageParser.Package pkg,
@UserIdInt int userId) {
InstantAppInfo uninstalledApp = createInstantAppInfoForPackage(
pkg, userId, false);
if (uninstalledApp == null) {
return;
}
if (mUninstalledInstantApps == null) {
mUninstalledInstantApps = new SparseArray<>();
}
List<UninstalledInstantAppState> uninstalledAppStates =
mUninstalledInstantApps.get(userId);
if (uninstalledAppStates == null) {
uninstalledAppStates = new ArrayList<>();
mUninstalledInstantApps.put(userId, uninstalledAppStates);
}
UninstalledInstantAppState uninstalledAppState = new UninstalledInstantAppState(
uninstalledApp, System.currentTimeMillis());
uninstalledAppStates.add(uninstalledAppState);
writeUninstalledInstantAppMetadata(uninstalledApp, userId);
writeInstantApplicationIconLPw(pkg, userId);
}
/**
* Add to / remove from {@link #mRunAnyRestrictedPackages}.
*/
@GuardedBy("mLock")
boolean updateForcedAppStandbyUidPackageLocked(int uid, @NonNull String packageName,
boolean restricted) {
final int index = findForcedAppStandbyUidPackageIndexLocked(uid, packageName);
final boolean wasRestricted = index >= 0;
if (wasRestricted == restricted) {
return false;
}
if (restricted) {
mRunAnyRestrictedPackages.add(Pair.create(uid, packageName));
} else {
mRunAnyRestrictedPackages.removeAt(index);
}
return true;
}
/**
* @hide
* Note that UserHandle.CURRENT will be interpreted at the time the
* activity is started, not when the pending intent is created.
*/
public static PendingIntent getActivitiesAsUser(Context context, int requestCode,
@NonNull Intent[] intents, int flags, Bundle options, UserHandle user) {
String packageName = context.getPackageName();
String[] resolvedTypes = new String[intents.length];
for (int i=0; i<intents.length; i++) {
intents[i].migrateExtraStreamToClipData();
intents[i].prepareToLeaveProcess(context);
resolvedTypes[i] = intents[i].resolveTypeIfNeeded(context.getContentResolver());
}
try {
IIntentSender target =
ActivityManager.getService().getIntentSender(
ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
null, null, requestCode, intents, resolvedTypes,
flags, options, user.getIdentifier());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Initialize day stats from the given state
*
* @param localDate The date for which stats are being tracked
* @param bucketBoundaries Bucket boundaries used from creating the buckets from
* @param stats Time spent in each of the buckets (in seconds)
* @hide
*/
public AmbientBrightnessDayStats(@NonNull LocalDate localDate,
@NonNull float[] bucketBoundaries, float[] stats) {
Preconditions.checkNotNull(localDate);
Preconditions.checkNotNull(bucketBoundaries);
Preconditions.checkArrayElementsInRange(bucketBoundaries, 0, Float.MAX_VALUE,
"bucketBoundaries");
if (bucketBoundaries.length < 1) {
throw new IllegalArgumentException("Bucket boundaries must contain at least 1 value");
}
checkSorted(bucketBoundaries);
if (stats == null) {
stats = new float[bucketBoundaries.length];
} else {
Preconditions.checkArrayElementsInRange(stats, 0, Float.MAX_VALUE, "stats");
if (bucketBoundaries.length != stats.length) {
throw new IllegalArgumentException(
"Bucket boundaries and stats must be of same size.");
}
}
mLocalDate = localDate;
mBucketBoundaries = bucketBoundaries;
mStats = stats;
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text,
@IntRange(from = 0) int start, @IntRange(from = 0) int end, float x,
int top, int y, int bottom, @NonNull Paint paint) {
Drawable b = getCachedDrawable();
canvas.save();
int transY = bottom - b.getBounds().bottom;
if (mVerticalAlignment == ALIGN_BASELINE) {
transY -= paint.getFontMetricsInt().descent;
}
canvas.translate(x, transY);
b.draw(canvas);
canvas.restore();
}
@Override
public Resources getResourcesForApplication(@NonNull ApplicationInfo app)
throws NameNotFoundException {
if (app.packageName.equals("system")) {
return mContext.mMainThread.getSystemUiContext().getResources();
}
final boolean sameUid = (app.uid == Process.myUid());
final Resources r = mContext.mMainThread.getTopLevelResources(
sameUid ? app.sourceDir : app.publicSourceDir,
sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
app.resourceDirs, app.sharedLibraryFiles, Display.DEFAULT_DISPLAY,
mContext.mPackageInfo);
if (r != null) {
return r;
}
throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
}
/**
* Return all installed and enabled packages.
*/
@NonNull
@VisibleForTesting
final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
final long start = getStatStartTime();
final long token = injectClearCallingIdentity();
try {
final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
all.removeIf(PACKAGE_NOT_INSTALLED);
return all;
} catch (RemoteException e) {
// Shouldn't happen.
Slog.wtf(TAG, "RemoteException", e);
return null;
} finally {
injectRestoreCallingIdentity(token);
logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
}
}
/**
* UsbAccessory should only be instantiated by UsbService implementation
* @hide
*/
public UsbAccessory(@NonNull String manufacturer, @NonNull String model,
@Nullable String description, @Nullable String version, @Nullable String uri,
@Nullable String serial) {
mManufacturer = Preconditions.checkNotNull(manufacturer);
mModel = Preconditions.checkNotNull(model);
mDescription = description;
mVersion = version;
mUri = uri;
mSerial = serial;
}
/**
* Merge additional metadata into this builder.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see RemoteInput#getExtras
*/
@NonNull
public Builder addExtras(@NonNull Bundle extras) {
if (extras != null) {
mExtras.putAll(extras);
}
return this;
}
/**
* Sets <a href="https://sqlite.org/pragma.html#pragma_journal_mode">journal mode</a>
* to use when {@link SQLiteDatabase#ENABLE_WRITE_AHEAD_LOGGING} flag is not set.
*/
@NonNull
public Builder setJournalMode(@NonNull String journalMode) {
Preconditions.checkNotNull(journalMode);
mJournalMode = journalMode;
return this;
}
boolean setCategory(@NonNull final String packageName, final int userId,
@Nullable String category) throws BadKeyException {
final int idx = select(packageName, userId);
if (idx < 0) {
throw new BadKeyException(packageName, userId);
}
return mItems.get(idx).setCategory(category);
}
/**
* Returns an {@link android.content.Intent} suitable for passing to
* {@link android.app.Activity#startActivityForResult(android.content.Intent, int)}
* which prompts the user to grant permissions to this application.
*
* @throws NullPointerException if {@code permissions} is {@code null} or empty.
*
* @hide
*/
public Intent buildRequestPermissionsIntent(@NonNull String[] permissions) {
if (ArrayUtils.isEmpty(permissions)) {
throw new NullPointerException("permission cannot be null or empty");
}
Intent intent = new Intent(ACTION_REQUEST_PERMISSIONS);
intent.putExtra(EXTRA_REQUEST_PERMISSIONS_NAMES, permissions);
intent.setPackage(getPermissionControllerPackageName());
return intent;
}
static @NonNull RadioManager.ModuleProperties
propertiesFromHal(int id, @NonNull String serviceName, @NonNull Properties prop,
@Nullable AmFmRegionConfig amfmConfig, @Nullable List<DabTableEntry> dabConfig) {
Objects.requireNonNull(serviceName);
Objects.requireNonNull(prop);
int[] supportedIdentifierTypes = prop.supportedIdentifierTypes.stream().
mapToInt(Integer::intValue).toArray();
int[] supportedProgramTypes = identifierTypesToProgramTypes(supportedIdentifierTypes);
return new RadioManager.ModuleProperties(
id,
serviceName,
// There is no Class concept in HAL 2.0.
RadioManager.CLASS_AM_FM,
prop.maker,
prop.product,
prop.version,
prop.serial,
/* HAL 2.0 only supports single tuner and audio source per
* HAL implementation instance. */
1, // numTuners
1, // numAudioSources
false, // isInitializationRequired
false, // isCaptureSupported
amfmConfigToBands(amfmConfig),
true, // isBgScanSupported is deprecated
supportedProgramTypes,
supportedIdentifierTypes,
dabConfigFromHal(dabConfig),
vendorInfoFromHal(prop.vendorInfo)
);
}
private static @Nullable
InstantAppInfo parseMetadata(@NonNull XmlPullParser parser,
@NonNull String packageName)
throws IOException, XmlPullParserException {
final int outerDepth = parser.getDepth();
while (XmlUtils.nextElementWithin(parser, outerDepth)) {
if (TAG_PACKAGE.equals(parser.getName())) {
return parsePackage(parser, packageName);
}
}
return null;
}
static @NonNull Map<String, Integer> readStringIntMap(@NonNull Parcel in) {
int size = in.readInt();
Map<String, Integer> map = new HashMap<>();
while (size-- > 0) {
String key = in.readString();
int value = in.readInt();
map.put(key, value);
}
return map;
}
@Override
public void invalidateDrawable(@NonNull Drawable dr) {
if (!mInDrawing) {
if (verifyDrawable(dr)) {
final Rect dirty = dr.getBounds();
final int scrollX = mScrollX + mPaddingLeft;
final int scrollY = mScrollY + mPaddingTop;
invalidate(dirty.left + scrollX, dirty.top + scrollY,
dirty.right + scrollX, dirty.bottom + scrollY);
} else {
super.invalidateDrawable(dr);
}
}
}
@VisibleForTesting
boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
synchronized (mLock) {
throwIfUserLockedL(userId);
final ShortcutUser user = getUserShortcutsLocked(userId);
// Always trust the cached component.
final ComponentName cached = user.getCachedLauncher();
if (cached != null) {
if (cached.getPackageName().equals(packageName)) {
return true;
}
}
// If the cached one doesn't match, then go ahead
final ComponentName detected = getDefaultLauncher(userId);
// Update the cache.
user.setLauncher(detected);
if (detected != null) {
if (DEBUG) {
Slog.v(TAG, "Detected launcher: " + detected);
}
return detected.getPackageName().equals(packageName);
} else {
// Default launcher not found.
return false;
}
}
}
/** @inheritDoc */
@Override
@NonNull
public WifiDeviceFilter build() {
markUsed();
return new WifiDeviceFilter(mNamePattern);
}
/**
* Set the server params for the user's key chain. This is used to uniquely identify a key
* chain. Along with the counter ID, it is used to uniquely identify an instance of a vault.
*/
public void setServerParams(@NonNull byte[] serverParams) throws RemoteException {
checkRecoverKeyStorePermission();
int userId = UserHandle.getCallingUserId();
int uid = Binder.getCallingUid();
byte[] currentServerParams = mDatabase.getServerParams(userId, uid);
if (Arrays.equals(serverParams, currentServerParams)) {
Log.v(TAG, "Not updating server params - same as old value.");
return;
}
long updatedRows = mDatabase.setServerParams(userId, uid, serverParams);
if (updatedRows < 0) {
throw new ServiceSpecificException(
ERROR_SERVICE_INTERNAL_ERROR, "Database failure trying to set server params.");
}
if (currentServerParams == null) {
Log.i(TAG, "Initialized server params.");
return;
}
if (mDatabase.getSnapshotVersion(userId, uid) != null) {
mDatabase.setShouldCreateSnapshot(userId, uid, true);
Log.i(TAG, "Updated server params. Snapshot must be updated");
} else {
Log.i(TAG, "Updated server params. Snapshot didn't exist");
}
}
/**
* Notify registered observers within the designated user(s) that a row was updated.
*
* @hide
*/
public void notifyChange(@NonNull Uri uri, ContentObserver observer, boolean syncToNetwork,
@UserIdInt int userHandle) {
try {
getContentService().notifyChange(
uri, observer == null ? null : observer.getContentObserver(),
observer != null && observer.deliverSelfNotifications(),
syncToNetwork ? NOTIFY_SYNC_TO_NETWORK : 0,
userHandle, mTargetSdkVersion);
} catch (RemoteException e) {
}
}
static @NonNull ProgramSelector programSelectorFromHal(
@NonNull android.hardware.broadcastradio.V2_0.ProgramSelector sel) {
ProgramSelector.Identifier[] secondaryIds = sel.secondaryIds.stream().
map(Convert::programIdentifierFromHal).map(Objects::requireNonNull).
toArray(ProgramSelector.Identifier[]::new);
return new ProgramSelector(
identifierTypeToProgramType(sel.primaryId.type),
Objects.requireNonNull(programIdentifierFromHal(sel.primaryId)),
secondaryIds, null);
}
private IpSecTunnelInterface(@NonNull Context ctx, @NonNull IIpSecService service,
@NonNull InetAddress localAddress, @NonNull InetAddress remoteAddress,
@NonNull Network underlyingNetwork)
throws ResourceUnavailableException, IOException {
mOpPackageName = ctx.getOpPackageName();
mService = service;
mLocalAddress = localAddress;
mRemoteAddress = remoteAddress;
mUnderlyingNetwork = underlyingNetwork;
try {
IpSecTunnelInterfaceResponse result =
mService.createTunnelInterface(
localAddress.getHostAddress(),
remoteAddress.getHostAddress(),
underlyingNetwork,
new Binder(),
mOpPackageName);
switch (result.status) {
case Status.OK:
break;
case Status.RESOURCE_UNAVAILABLE:
throw new ResourceUnavailableException(
"No more tunnel interfaces may be allocated by this requester.");
default:
throw new RuntimeException(
"Unknown status returned by IpSecService: " + result.status);
}
mResourceId = result.resourceId;
mInterfaceName = result.interfaceName;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
mCloseGuard.open("constructor");
}
/**
* Returns the text classifier that was set via {@link #setTextClassifier(TextClassifier)}.
* If this is null, this method returns a default text classifier (i.e. either the system text
* classifier if one exists, or a local text classifier running in this app.)
*
* @see #setTextClassifier(TextClassifier)
*/
@NonNull
public TextClassifier getTextClassifier() {
synchronized (mLock) {
if (mCustomTextClassifier != null) {
return mCustomTextClassifier;
} else if (isSystemTextClassifierEnabled()) {
return getSystemTextClassifier();
} else {
return getLocalTextClassifier();
}
}
}
/**
* Relinquish a persisted URI permission grant. The URI must have been
* previously made persistent with
* {@link #takePersistableUriPermission(Uri, int)}. Any non-persistent
* grants to the calling package will remain intact.
*
* @see #getPersistedUriPermissions()
*/
public void releasePersistableUriPermission(@NonNull Uri uri,
@Intent.AccessUriMode int modeFlags) {
Preconditions.checkNotNull(uri, "uri");
try {
ActivityManager.getService().releasePersistableUriPermission(
ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
} catch (RemoteException e) {
}
}
boolean signaturesMatching(@NonNull String packageName1, @NonNull String packageName2,
int userId);
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
writeToParcelInternal(dest, flags);
}
/** @hide */
@Override
public @NonNull List<SharedLibraryInfo> getSharedLibraries(int flags) {
return getSharedLibrariesAsUser(flags, mContext.getUserId());
}
/**
* Creates a new Passthrough of the specfied MetricAffectingSpan.
*/
Passthrough(@NonNull MetricAffectingSpan cs) {
mStyle = cs;
}
void appRemovedOrHidden(@NonNull AppWindowToken appWindow) {
if (DEBUG_UNKNOWN_APP_VISIBILITY) {
Slog.d(TAG, "App removed or hidden appWindow=" + appWindow);
}
mUnknownApps.remove(appWindow);
}
private String getIdmapPath(@NonNull final String baseCodePath) {
final StringBuilder sb = new StringBuilder("/data/resource-cache/");
sb.append(baseCodePath.substring(1).replace('/', '@'));
sb.append("@idmap");
return sb.toString();
}