public static Package callParsePackage(Path apkFile) {
    PackageParser packageParser = new PackageParser();

    int flags = PackageParser.PARSE_IGNORE_PROCESSES;
    try {
      Package thePackage;
      if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.LOLLIPOP) {
        // TODO(christianw/brettchabot): workaround for NPE from probable bug in Q.
        // Can be removed when upstream properly handles a null callback
        // PackageParser#setMinAspectRatio(Package)
        if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.Q) {
          QHelper.setCallback(packageParser);
        }
        thePackage = packageParser.parsePackage(apkFile.toFile(), flags);
      } else { // JB -> KK
        thePackage =
            reflector(_PackageParser_.class, packageParser)
                .parsePackage(
                    apkFile.toFile(), Fs.externalize(apkFile), new DisplayMetrics(), flags);
      }

      if (thePackage == null) {
        List<LogItem> logItems = ShadowLog.getLogsForTag("PackageParser");
        if (logItems.isEmpty()) {
          throw new RuntimeException(
              "Failed to parse package " + apkFile);
        } else {
          LogItem logItem = logItems.get(0);
          throw new RuntimeException(
              "Failed to parse package " + apkFile + ": " + logItem.msg, logItem.throwable);
        }
      }

      return thePackage;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

Parses an AndroidManifest.xml file using the framework PackageParser.

Parses an AndroidManifest . xml file using the framework PackageParser .


@Override
  public Intent getIntentForActivity(Class<? extends Activity> activityClass) {
    PackageManager packageManager = getTargetContext().getPackageManager();
    ComponentName componentName = new ComponentName(getTargetContext(), activityClass);
    Intent intent = Intent.makeMainActivity(componentName);
    if (packageManager.resolveActivity(intent, 0) != null) {
      return intent;
    }
    return Intent.makeMainActivity(new ComponentName(getContext(), activityClass));
  }

@ Override public Intent getIntentForActivity ( Class < ? extends Activity > activityClass ) { PackageManager packageManager = getTargetContext ( ) . getPackageManager ( ) ; ComponentName componentName = new ComponentName ( getTargetContext ( ) , activityClass ) ; Intent intent = Intent . makeMainActivity ( componentName ) ; if ( packageManager . resolveActivity ( intent , 0 ) != null ) { return intent ; } return Intent . makeMainActivity ( new ComponentName ( getContext ( ) , activityClass ) ) ; }

This implementation makes sure, that the activity you are trying to launch exists

This implementation makes sure that the activity you are trying to launch exists


static boolean VerifyResTableType(ResTable_type header) {
    if (header.id == 0) {
      logError("RES_TABLE_TYPE_TYPE has invalid ID 0.");
      return false;
    }

    int entry_count = dtohl(header.entryCount);
    // if (entry_count > std.numeric_limits<uint16_t>.max()) {
    if (entry_count > 0xffff) {
      logError("RES_TABLE_TYPE_TYPE has too many entries (" + entry_count + ").");
      return false;
    }

    // Make sure that there is enough room for the entry offsets.
    int offsets_offset = dtohs(header.header.headerSize);
    int entries_offset = dtohl(header.entriesStart);
    int offsets_length = 4 * entry_count;

    if (offsets_offset > entries_offset || entries_offset - offsets_offset < offsets_length) {
      logError("RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data.");
      return false;
    }

    if (entries_offset > dtohl(header.header.size)) {
      logError("RES_TABLE_TYPE_TYPE entry offsets extend beyond chunk.");
      return false;
    }

    if (isTruthy(entries_offset & 0x03)) {
      logError("RES_TABLE_TYPE_TYPE entries start at unaligned address.");
      return false;
    }
    return true;
  }


private static List<ManifestIdentifier> findLibraries(Path resDirectory) throws IOException {
    List<ManifestIdentifier> libraryBaseDirs = new ArrayList<>();

    if (resDirectory != null) {
      Path baseDir = resDirectory.getParent();
      final Properties properties = getProperties(baseDir.resolve("project.properties"));
      Properties overrideProperties = getProperties(baseDir.resolve("test-project.properties"));
      properties.putAll(overrideProperties);

      int libRef = 1;
      String lib;
      while ((lib = properties.getProperty("android.library.reference." + libRef)) != null) {
        Path libraryDir = baseDir.resolve(lib);
        if (Files.isDirectory(libraryDir)) {
          // Ignore directories without any files
          Path[] libraryBaseDirFiles = Fs.listFiles(libraryDir);
          if (libraryBaseDirFiles != null && libraryBaseDirFiles.length > 0) {
            List<ManifestIdentifier> libraries =
                findLibraries(libraryDir.resolve(Config.DEFAULT_RES_FOLDER));
            libraryBaseDirs.add(
                new ManifestIdentifier(
                    null,
                    libraryDir.resolve(Config.DEFAULT_MANIFEST_NAME),
                    libraryDir.resolve(Config.DEFAULT_RES_FOLDER),
                    libraryDir.resolve(Config.DEFAULT_ASSET_FOLDER),
                    libraries));
          }
        }

        libRef++;
      }
    }
    return libraryBaseDirs;
  }

private
static
List
<
ManifestIdentifier
>
findLibraries
(
Path
resDirectory
)
throws
IOException
{
List
<
ManifestIdentifier
>
libraryBaseDirs
=
new
ArrayList
<>
(
)
;
if
(
resDirectory
!=
)
{
Path
baseDir
=
resDirectory
.
getParent
(
)
;
final
Properties
properties
=
getProperties
(
baseDir
.
resolve
(
"project.properties"
)
)
;
Properties
overrideProperties
=
getProperties
(
baseDir
.
resolve
(
"test-project.properties"
)
)
;
properties
.
putAll
(
overrideProperties
)
;
int
libRef
=
1
;
String
lib
;
while
(
(
lib
=
properties
.
getProperty
(
"android.library.reference."
+
libRef
)
)
!=
)
{
Path
libraryDir
=
baseDir
.
resolve
(
lib
)
;
if
(
Files
.
isDirectory
(
libraryDir
)
)
{
// Ignore directories without any files
Path
[
]
libraryBaseDirFiles
=
Fs
.
listFiles
(
libraryDir
)
;
if
(
libraryBaseDirFiles
!=
&&
libraryBaseDirFiles
.
length
>
0
)
{
List
<
ManifestIdentifier
>
libraries
=
findLibraries
(
libraryDir
.
resolve
(
Config
.
DEFAULT_RES_FOLDER
)
)
;
libraryBaseDirs
.
add
(
new
ManifestIdentifier
(
,
libraryDir
.
resolve
(
Config
.
DEFAULT_MANIFEST_NAME
)
,
libraryDir
.
resolve
(
Config
.
DEFAULT_RES_FOLDER
)
,
libraryDir
.
resolve
(
Config
.
DEFAULT_ASSET_FOLDER
)
,
libraries
)
)
;
}
}
libRef
++
;
}
}
return
libraryBaseDirs
;
}

Find valid library AndroidManifest files referenced from an already loaded AndroidManifest's
`project.properties` file, recursively.

Find valid library AndroidManifest files referenced from an already loaded AndroidManifest s project . properties file recursively .


@Implementation(minSdk = N)
  @Nullable
  protected CharSequence getOrganizationName(ComponentName admin) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      enforceDeviceOwnerOrProfileOwner(admin);
    } else {
      enforceProfileOwner(admin);
    }

    return organizationName;
  }

@ Implementation ( minSdk = N ) @ Nullable protected CharSequence getOrganizationName ( ComponentName admin ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . O ) { enforceDeviceOwnerOrProfileOwner ( admin ) ; } else { enforceProfileOwner ( admin ) ; } return organizationName ; }

Returns organization name.

The API can only be called by profile owner since Android N.

Android framework has a hidden API for getting the organization name for device owner since
Android O. This method, however, is extended to return the organization name for device owners
too to make testing of {@link #setOrganizationName(ComponentName, CharSequence)} easier for
device owner cases.


@Implementation(minSdk = LOLLIPOP)
  protected boolean setPermittedAccessibilityServices(
      ComponentName admin, List<String> packageNames) {
    enforceDeviceOwnerOrProfileOwner(admin);
    permittedAccessibilityServices = packageNames;
    return true;
  }

@ Implementation ( minSdk = LOLLIPOP ) protected boolean setPermittedAccessibilityServices ( ComponentName admin , List < String > packageNames ) { enforceDeviceOwnerOrProfileOwner ( admin ) ; permittedAccessibilityServices = packageNames ; return true ; }

Sets permitted accessibility services.

The API can be called by either a profile or device owner.

This method does not check already enabled non-system accessibility services, so will always
set the restriction and return true.


@Implementation(minSdk = LOLLIPOP)
  protected boolean setPermittedInputMethods(ComponentName admin, List<String> packageNames) {
    enforceDeviceOwnerOrProfileOwner(admin);
    permittedInputMethods = packageNames;
    return true;
  }

@ Implementation ( minSdk = LOLLIPOP ) protected boolean setPermittedInputMethods ( ComponentName admin , List < String > packageNames ) { enforceDeviceOwnerOrProfileOwner ( admin ) ; permittedInputMethods = packageNames ; return true ; }

Sets permitted input methods.

The API can be called by either a profile or device owner.

This method does not check already enabled non-system input methods, so will always set the
restriction and return true.


public boolean activateResetToken(ComponentName admin) {
    if (!passwordResetTokens.containsKey(admin)) {
      throw new IllegalArgumentException("No token set for comopnent: " + admin);
    }
    return componentsWithActivatedTokens.add(admin);
  }

public
boolean
activateResetToken
(
ComponentName
admin
)
{
if
(
!
passwordResetTokens
.
containsKey
(
admin
)
)
{
throw
new
IllegalArgumentException
(
"No token set for comopnent: "
+
admin
)
;
}
return
componentsWithActivatedTokens
.
add
(
admin
)
;
}

Activates reset token for given admin.

@param admin Which {@link DeviceAdminReceiver} this request is associated with.
@return if the activation state changed.
@throws IllegalArgumentException if there is no token set for this admin.


public Set<ResTable_config> GetResourceConfigurations(boolean exclude_system,
      boolean exclude_mipmap) {
    // ATRACE_NAME("AssetManager::GetResourceConfigurations");
    Set<ResTable_config> configurations = new HashSet<>();
    for (final PackageGroup package_group : package_groups_) {
      for (final ConfiguredPackage package_ : package_group.packages_) {
        if (exclude_system && package_.loaded_package_.IsSystem()) {
          continue;
        }
        package_.loaded_package_.CollectConfigurations(exclude_mipmap, configurations);
      }
    }
    return configurations;
  }


public Set<String> GetResourceLocales(boolean exclude_system,
      boolean merge_equivalent_languages) {
    ATRACE_CALL();
    Set<String> locales = new HashSet<>();
    for (final PackageGroup package_group : package_groups_) {
      for (final ConfiguredPackage package_ : package_group.packages_) {
        if (exclude_system && package_.loaded_package_.IsSystem()) {
          continue;
        }
        package_.loaded_package_.CollectLocales(merge_equivalent_languages, locales);
      }
    }
    return locales;
  }

public Set < String > GetResourceLocales ( boolean exclude_system , boolean merge_equivalent_languages ) { ATRACE_CALL ( ) ; Set < String > locales = new HashSet <> ( ) ; for ( final PackageGroup package_group : package_groups_ ) { for ( final ConfiguredPackage package_ : package_group . packages_ ) { if ( exclude_system && package_ . loaded_package_ . IsSystem ( ) ) { continue ; } package_ . loaded_package_ . CollectLocales ( merge_equivalent_languages , locales ) ; } } return locales ; }

boolean merge_equivalent_languages = false);

boolean merge_equivalent_languages = false ) ;


public Asset OpenNonAsset(final String filename,
      Asset.AccessMode mode,
      Ref<ApkAssetsCookie> out_cookie) {
    ATRACE_CALL();
    for (int i = apk_assets_.size() - 1; i >= 0; i--) {
      Asset asset = apk_assets_.get(i).Open(filename, mode);
      if (isTruthy(asset)) {
        if (out_cookie != null) {
          out_cookie.set(ApkAssetsCookie.forInt(i));
        }
        return asset;
      }
    }

    if (out_cookie != null) {
      out_cookie.set(K_INVALID_COOKIE);
    }
    return null;
  }

public Asset OpenNonAsset ( final String filename , Asset . AccessMode mode , Ref < ApkAssetsCookie > out_cookie ) { ATRACE_CALL ( ) ; for ( int i = apk_assets_ . size ( ) - 1 ; i >= 0 ; i -- ) { Asset asset = apk_assets_ . get ( i ) . Open ( filename , mode ) ; if ( isTruthy ( asset ) ) { if ( out_cookie != null ) { out_cookie . set ( ApkAssetsCookie . forInt ( i ) ) ; } return asset ; } } if ( out_cookie != null ) { out_cookie . set ( K_INVALID_COOKIE ) ; } return null ; }


public void addAvailableRestoreSets(long restoreToken, List<String> packages) {
    serviceState.restoreData.put(restoreToken, packages);
  }

public void addAvailableRestoreSets ( long restoreToken , List < String > packages ) { serviceState . restoreData . put ( restoreToken , packages ) ; }

Adds a restore set available to be restored.

Adds a restore set available to be restored .


@Override
  public void runPaused(Runnable runnable) {
    if (isPaused && Thread.currentThread() == realLooper.getThread()) {
      // just run
      runnable.run();
    } else {
      throw new UnsupportedOperationException();
    }
  }

@
Override
public
void
runPaused
(
Runnable
runnable
)
{
if
(
isPaused
&&
Thread
.
currentThread
(
)
==
realLooper
.
getThread
(
)
)
{
// just run
runnable
.
run
(
)
;
}
else
{
throw
new
UnsupportedOperationException
(
)
;
}
}


private void executeOnLooper(ControlRunnable runnable) {
    if (Thread.currentThread() == realLooper.getThread()) {
      runnable.run();
    } else {
      if (realLooper.equals(Looper.getMainLooper())) {
        throw new UnsupportedOperationException(
            "main looper can only be controlled from main thread");
      }
      looperExecutor.execute(runnable);
      runnable.waitTillComplete();
    }
  }

Executes the given runnable on the loopers thread, and waits for it to complete.

Executes the given runnable on the loopers thread and waits for it to complete .


@Implementation(maxSdk = JELLY_BEAN_MR1)
  @SuppressWarnings("TypeParameterUnusedInFormals")
  protected <T extends Parcelable> T readParcelable(ClassLoader loader) {
    // prior to JB MR2, readParcelableCreator() is inlined here.
    Parcelable.Creator<?> creator = readParcelableCreator(loader);
    if (creator == null) {
      return null;
    }

    if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
      Parcelable.ClassLoaderCreator<?> classLoaderCreator =
          (Parcelable.ClassLoaderCreator<?>) creator;
      return (T) classLoaderCreator.createFromParcel(realObject, loader);
    }
    return (T) creator.createFromParcel(realObject);
  }

this needs to start above 0, which is a magic number to Parcel

this needs to start above 0 which is a magic number to Parcel


@Implementation(minSdk = M)
  protected void writeBlob(byte[] b, int offset, int len) {
    if (b == null) {
      realObject.writeInt(-1);
      return;
    }
    throwsIfOutOfBounds(b.length, offset, len);
    long nativePtr = ReflectionHelpers.getField(realObject, "mNativePtr");
    nativeWriteBlob(nativePtr, b, offset, len);
  }

@ Implementation ( minSdk = M ) protected void writeBlob ( byte [ ] b , int offset , int len ) { if ( b == null ) { realObject . writeInt ( - 1 ) ; return ; } throwsIfOutOfBounds ( b . length , offset , len ) ; long nativePtr = ReflectionHelpers . getField ( realObject , "mNativePtr" ) ; nativeWriteBlob ( nativePtr , b , offset , len ) ; }

non - existent - in - JDK java . util . Arrays . checkOffsetAndCount method .


@Implementation(minSdk = LOLLIPOP)
  protected static void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len) {
    nativeWriteByteArray(nativePtr, b, offset, len);
  }

@ Implementation ( minSdk = LOLLIPOP ) protected static void nativeWriteBlob ( long nativePtr , byte [ ] b , int offset , int len ) { nativeWriteByteArray ( nativePtr , b , offset , len ) ; }

nativeWriteBlob was introduced in lollipop, thus no need for a int nativePtr variant

nativeWriteBlob was introduced in lollipop thus no need for a int nativePtr variant


public byte[] toByteArray() {
      int oldDataPosition = dataPosition;
      try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        // NOTE: Serializing the data array would be simpler, and serialization would actually
        // preserve reference equality between entries.  However, the length-encoded format here
        // preserves the previous format, which some tests appear to rely on.
        List<FakeEncodedItem> entries = new ArrayList<>();
        // NOTE: Use readNextItem to scan so the contents can be proactively validated.
        dataPosition = 0;
        while (dataPosition < dataSize) {
          entries.add(readNextItem(Object.class));
        }
        oos.writeInt(entries.size());
        for (FakeEncodedItem item : entries) {
          oos.writeInt(item.sizeBytes);
          oos.writeObject(item.value);
        }
        oos.flush();
        return bos.toByteArray();
      } catch (IOException e) {
        throw new UnreliableBehaviorError("ErrorProne unable to serialize its custom format", e);
      } finally {
        dataPosition = oldDataPosition;
      }
    }

Converts a ByteBuffer to a raw byte array. This method should be symmetrical with
fromByteArray.

Converts a ByteBuffer to a raw byte array . This method should be symmetrical with fromByteArray .


public void setDataPosition(int pos) {
      if (pos > dataSize) {
        // NOTE: Real parcel ignores this until a write occurs.
        throw new UnreliableBehaviorError(pos + " greater than dataSize " + dataSize);
      }
      dataPosition = pos;
      failNextReadIfPastEnd = false;
    }

Sets the current data position.

@param pos
Desired position in bytes


private void checkConsistentReadAndIncrementPosition(Class<?> clazz, FakeEncodedItem item) {
      int endPosition = dataPosition + item.sizeBytes;
      for (int i = dataPosition; i < endPosition; i++) {
        FakeEncodedItem foundItemItem = i < dataSize ? data[i] : null;
        if (foundItemItem != item) {
          throw new UnreliableBehaviorError(
              clazz,
              dataPosition,
              item,
              String.format(
                  Locale.US,
                  "but [%s] interrupts it at position %d",
                  foundItemItem == null
                      ? "uninitialized data or the end of the buffer"
                      : foundItemItem.value,
                  i));
        }
      }
      dataPosition = Math.min(dataSize, dataPosition + item.sizeBytes);
    }

Ensures that the next sizeBytes are all the initial value we read.

This detects:

Reading an item, but not starting at its start position

Reading items that were truncated by setSize

Reading items that were partially overwritten by another

Ensures that the next sizeBytes are all the initial value we read .


private Object peek() {
      return dataPosition < dataSize && data[dataPosition] != null
          ? data[dataPosition].value
          : null;
    }

private Object peek ( ) { return dataPosition < dataSize && data [ dataPosition ] != null ? data [ dataPosition ] . value : null ; }

Returns the item at the current position, or null if uninitialized or null.

Returns the item at the current position or null if uninitialized or null .


private <T> FakeEncodedItem readNextItem(Class<T> clazz) {
      FakeEncodedItem item = data[dataPosition];
      if (item == null) {
        // While Parcel will treat these as zeros, in tests, this is almost always an error.
        throw new UnreliableBehaviorError("Reading uninitialized data at position " + dataPosition);
      }
      checkConsistentReadAndIncrementPosition(clazz, item);
      return item;
    }

Reads a complete item in the byte buffer.

@param clazz this is the type that is being read, but not checked in this method
@return null if the default value should be returned, otherwise the item holding the data

Reads a complete item in the byte buffer .


private <T> T readValue(T pastEndValue, Class<T> clazz, boolean allowNull) {
      if (dataPosition >= dataSize) {
        // Normally, reading past the end is permitted, and returns the default values.  However,
        // writing to a parcel then reading without setting the position back to 0 is an incredibly
        // common error to make in tests, and should never really happen in production code, so
        // this shadow will fail in this condition.
        if (failNextReadIfPastEnd) {
          throw new UnreliableBehaviorError(
              "Did you forget to setDataPosition(0) before reading the parcel?");
        }
        return pastEndValue;
      }
      int startPosition = dataPosition;
      FakeEncodedItem item = readNextItem(clazz);
      if (item == null) {
        return pastEndValue;
      } else if (item.value == null && allowNull) {
        return null;
      } else if (clazz.isInstance(item.value)) {
        return clazz.cast(item.value);
      } else {
        // Numerous existing tests rely on ShadowParcel throwing RuntimeException and catching
        // them.  Many of these tests are trying to test what happens when an invalid Parcel is
        // provided.  However, Android has no concept of an "invalid parcel" because Parcel will
        // happily return garbage if you ask for it.  The only runtime exceptions are thrown on
        // array length mismatches, or higher-level APIs like Parcelable (which has its own safety
        // checks).  Tests trying to test error-handling behavior should instead craft a Parcel
        // that specifically triggers a BadParcelableException.
        throw new RuntimeException(
            new UnreliableBehaviorError(
                clazz, startPosition, item, "and it is non-portable to reinterpret it"));
      }
    }

Reads the next value in the byte buffer of a specified type.

@param pastEndValue value to return when reading past the end of the buffer
@param clazz this is the type that is being read, but not checked in this method
@param allowNull whether null values are permitted

Reads the next value in the byte buffer of a specified type .


private boolean readZeroes(int bytes) {
      int endPosition = dataPosition + bytes;
      if (endPosition > dataSize) {
        return false;
      }
      for (int i = dataPosition; i < endPosition; i++) {
        if (data[i] == null || !data[i].isEncodedAsAllZeroBytes) {
          return false;
        }
      }
      // Note in this case we short-circuit other verification -- even if we are reading weirdly
      // clobbered zeroes, they're still zeroes.  Future reads might fail, though.
      dataPosition = endPosition;
      return true;
    }

Determines if there is a sequence of castable zeroes, and consumes them.

<p>This is the only exception for strong typing, because zero bytes are portable and
unambiguous. There are a few situations where well-written code can rely on this, so it is
worthwhile making a special exception for. This tolerates partially-overwritten and truncated
values if all bytes are zero.

Determines if there is a sequence of castable zeroes and consumes them .


private <T> T readPrimitive(int defaultSizeBytes, T defaultValue, Class<T> clazz) {
      // Check for zeroes first, since partially-overwritten values are not an error for zeroes.
      if (readZeroes(defaultSizeBytes)) {
        return defaultValue;
      }
      return readValue(defaultValue, clazz, /* allowNull= */ false);
    }

Reads a primitive, which may reinterpret zeros of other types.

@param defaultSizeBytes if reinterpreting zeros, the number of bytes to consume
@param defaultValue the default value for zeros or reading past the end
@param clazz this is the type that is being read, but not checked in this method

Reads a primitive which may reinterpret zeros of other types .


private void writeItem(FakeEncodedItem item) {
      int endPosition = dataPosition + item.sizeBytes;
      if (endPosition > data.length) {
        // Parcel grows by 3/2 of the new size.
        setDataCapacityAtLeast(endPosition * 3 / 2);
      }
      if (endPosition > dataSize) {
        failNextReadIfPastEnd = true;
        dataSize = endPosition;
      }
      Arrays.fill(data, dataPosition, endPosition, item);
      dataPosition = endPosition;
    }

private
void
writeItem
(
FakeEncodedItem
item
)
{
int
endPosition
=
dataPosition
+
item
.
sizeBytes
;
if
(
endPosition
>
data
.
length
)
{
// Parcel grows by 3/2 of the new size.
setDataCapacityAtLeast
(
endPosition
*
3
/
2
)
;
}
if
(
endPosition
>
dataSize
)
{
failNextReadIfPastEnd
=
true
;
dataSize
=
endPosition
;
}
Arrays
.
fill
(
data
,
dataPosition
,
endPosition
,
item
)
;
dataPosition
=
endPosition
;
}

Writes an encoded item directly, bypassing alignment, and possibly repeating an item.

Writes an encoded item directly bypassing alignment and possibly repeating an item .


public static byte[] readBytes(InputStream is) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream(is.available())) {
      copy(is, bos);
      return bos.toByteArray();
    }
  }

public static byte [ ] readBytes ( InputStream is ) throws IOException { try ( ByteArrayOutputStream bos = new ByteArrayOutputStream ( is . available ( ) ) ) { copy ( is , bos ) ; return bos . toByteArray ( ) ; } }

This method consumes an input stream and returns its content.

@param is The input stream to read from.
@return The bytes read from the stream.
@throws IOException Error reading from stream.

This method consumes an input stream and returns its content .


@Deprecated
  public synchronized long getNativeObjectId(T o) {
    checkNotNull(o);
    Long nativeId = nativeObjToIdMap.inverse().get(o);
    if (nativeId == null) {
      nativeId = nextId;
      if (debug) {
        System.out.printf("NativeObjRegistry %s: register %d -> %s%n", name, nativeId, o);
      }
      nativeObjToIdMap.put(nativeId, o);
      nextId++;
    }
    return nativeId;
  }

Retrieve the native id for given object. Assigns a new unique id to the object if not
previously registered.

@deprecated Use {@link #register(Object)} instead.

Retrieve the native id for given object . Assigns a new unique id to the object if not previously registered .


public synchronized T getNativeObject(long nativeId) {
    T object = nativeObjToIdMap.get(nativeId);
    if (object != null) {
      return object;
    } else {
      throw new NullPointerException(
          String.format(
              "Could not find object with nativeId: %d. Currently registered ids: %s",
              nativeId, nativeObjToIdMap.keySet()));
    }
  }

Retrieve the native object for given id. Throws if object with that id cannot be found

Retrieve the native object for given id . Throws if object with that id cannot be found


public void callAttach(Context context) {
    ReflectionHelpers.callInstanceMethod(Application.class, realApplication, "attach",
        ReflectionHelpers.ClassParameter.from(Context.class, context));
  }

public void callAttach ( Context context ) { ReflectionHelpers . callInstanceMethod ( Application . class , realApplication , "attach" , ReflectionHelpers . ClassParameter . from ( Context . class , context ) ) ; }

Attaches an application to a base context.

@param context The context with which to initialize the application, whose base context will
be attached to the application

Attaches an application to a base context .


public void setDefaultNetworkActive(boolean isActive) {
    defaultNetworkActive = isActive;
    if (defaultNetworkActive) {
      for (ConnectivityManager.OnNetworkActiveListener l : onNetworkActiveListeners) {
        if (l != null) {
          l.onNetworkActive();
        }
      }
    }
  }

public void setDefaultNetworkActive ( boolean isActive ) { defaultNetworkActive = isActive ; if ( defaultNetworkActive ) { for ( ConnectivityManager . OnNetworkActiveListener l : onNetworkActiveListeners ) { if ( l != null ) { l . onNetworkActive ( ) ; } } } }

Sets the active state of the default network.

By default this is true and affects the result of {@link
ConnectivityManager#isActiveNetworkMetered()}, {@link
ConnectivityManager#isDefaultNetworkActive()}, {@link ConnectivityManager#getActiveNetwork()}
and {@link ConnectivityManager#getAllNetworkInfo()}.

Calling this method with {@code true} after any listeners have been registered with {@link
ConnectivityManager#addDefaultNetworkActiveListener(OnNetworkActiveListener)} will result in
those listeners being fired.

@param isActive The active state of the default network.

Sets the active state of the default network .


@Implementation(maxSdk = LOLLIPOP_MR1)
  protected int play(
      int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) {
    playedSounds.add(new Playback(soundID, leftVolume, rightVolume, priority, loop, rate));
    return 1;
  }

@ Implementation ( maxSdk = LOLLIPOP_MR1 ) protected int play ( int soundID , float leftVolume , float rightVolume , int priority , int loop , float rate ) { playedSounds . add ( new Playback ( soundID , leftVolume , rightVolume , priority , loop , rate ) ) ; return 1 ; }


@Implementation
  protected int load(String path, int priority) {
    int soundId = soundIds.getAndIncrement();
    idToPaths.put(soundId, path);
    return soundId;
  }

@ Implementation protected int load ( String path , int priority ) { int soundId = soundIds . getAndIncrement ( ) ; idToPaths . put ( soundId , path ) ; return soundId ; }

FileDescriptor which would make it difficult to check if a given sound has been placed.

FileDescriptor which would make it difficult to check if a given sound has been placed .


public void reconstructWidgetViewAsIfPhoneWasRotated(int appWidgetId) {
    WidgetInfo widgetInfo = widgetInfos.get(appWidgetId);
    widgetInfo.view = createWidgetView(widgetInfo.layoutId);
    widgetInfo.lastRemoteViews.reapply(context, widgetInfo.view);
  }

Triggers a reapplication of the most recent set of actions against the widget, which is what happens when the
phone is rotated. Does not attempt to simulate a change in screen geometry.

@param appWidgetId the ID of the widget to be affected

Triggers a reapplication of the most recent set of actions against the widget which is what happens when the phone is rotated . Does not attempt to simulate a change in screen geometry .


public int[] createWidgets(Class<? extends AppWidgetProvider> appWidgetProviderClass, int widgetLayoutId, int howManyToCreate) {
    AppWidgetProvider appWidgetProvider = ReflectionHelpers.callConstructor(appWidgetProviderClass);

    int[] newWidgetIds = new int[howManyToCreate];
    for (int i = 0; i < howManyToCreate; i++) {
      View widgetView = createWidgetView(widgetLayoutId);

      int myWidgetId = nextWidgetId++;
      widgetInfos.put(myWidgetId, new WidgetInfo(widgetView, widgetLayoutId, appWidgetProvider));
      newWidgetIds[i] = myWidgetId;
    }

    appWidgetProvider.onUpdate(context, realAppWidgetManager, newWidgetIds);
    return newWidgetIds;
  }

public int [ ] createWidgets ( Class < ? extends AppWidgetProvider > appWidgetProviderClass , int widgetLayoutId , int howManyToCreate ) { AppWidgetProvider appWidgetProvider = ReflectionHelpers . callConstructor ( appWidgetProviderClass ) ; int [ ] newWidgetIds = new int [ howManyToCreate ] ; for ( int i = 0 ; i < howManyToCreate ; i ++ ) { View widgetView = createWidgetView ( widgetLayoutId ) ; int myWidgetId = nextWidgetId ++ ; widgetInfos . put ( myWidgetId , new WidgetInfo ( widgetView , widgetLayoutId , appWidgetProvider ) ) ; newWidgetIds [ i ] = myWidgetId ; } appWidgetProvider . onUpdate ( context , realAppWidgetManager , newWidgetIds ) ; return newWidgetIds ; }

Creates a bunch of widgets by inflating the same layout multiple times.

@param appWidgetProviderClass the app widget provider class
@param widgetLayoutId         id of the layout to inflate
@param howManyToCreate        number of new widgets to create
@return the IDs of the new widgets

Creates a bunch of widgets by inflating the same layout multiple times .


public void invokeSeekCompleteListener() {
    int duration = getMediaInfo().duration;
    setCurrentPosition(pendingSeek > duration ? duration
        : pendingSeek < 0 ? 0 : pendingSeek);
    pendingSeek = -1;
    if (state == STARTED) {
      doStart();
    }
    if (seekCompleteListener == null) {
      return;
    }
    seekCompleteListener.onSeekComplete(player);
  }

public void invokeSeekCompleteListener ( ) { int duration = getMediaInfo ( ) . duration ; setCurrentPosition ( pendingSeek > duration ? duration : pendingSeek < 0 ? 0 : pendingSeek ) ; pendingSeek = - 1 ; if ( state == STARTED ) { doStart ( ) ; } if ( seekCompleteListener == null ) { return ; } seekCompleteListener . onSeekComplete ( player ) ; }

Allows test cases to simulate seek completion by invoking callback.

Allows test cases to simulate seek completion by invoking callback .


public void invokeInfoListener(int what, int extra) {
    if (infoListener != null) {
      infoListener.onInfo(player, what, extra);
    }
  }

public void invokeInfoListener ( int what , int extra ) { if ( infoListener != null ) { infoListener . onInfo ( player , what , extra ) ; } }

Allows test cases to directly simulate invocation of the OnInfo event.

@param what
parameter to pass in to {@code what} in
{@link MediaPlayer.OnInfoListener#onInfo(MediaPlayer, int, int)}.
@param extra
parameter to pass in to {@code extra} in
{@link MediaPlayer.OnInfoListener#onInfo(MediaPlayer, int, int)}.

Allows test cases to directly simulate invocation of the OnInfo event .


public void invokeErrorListener(int what, int extra) {
    // Calling doStop() un-schedules the next event and
    // stops normal event flow from continuing.
    doStop();
    state = ERROR;
    boolean handled = errorListener != null
        && errorListener.onError(player, what, extra);
    if (!handled) {
      // The documentation isn't very clear if onCompletion is
      // supposed to be called from non-playing states
      // (ie, states other than STARTED or PAUSED). Testing
      // revealed that onCompletion is invoked even if playback
      // hasn't started or is not in progress.
      invokeCompletionListener();
      // Need to set this again because
      // invokeCompletionListener() will set the state
      // to PLAYBACK_COMPLETED
      state = ERROR;
    }
  }

Allows test cases to directly simulate invocation of the OnError event.

@param what
parameter to pass in to {@code what} in
{@link MediaPlayer.OnErrorListener#onError(MediaPlayer, int, int)}.
@param extra
parameter to pass in to {@code extra} in
{@link MediaPlayer.OnErrorListener#onError(MediaPlayer, int, int)}.

Allows test cases to directly simulate invocation of the OnError event .


public static Display getDefaultDisplay() {
    WindowManager windowManager =
        (WindowManager) RuntimeEnvironment.application.getSystemService(Context.WINDOW_SERVICE);
    return windowManager.getDefaultDisplay();
  }

public static Display getDefaultDisplay ( ) { WindowManager windowManager = ( WindowManager ) RuntimeEnvironment . application . getSystemService ( Context . WINDOW_SERVICE ) ; return windowManager . getDefaultDisplay ( ) ; }

Returns the default display.

@return the default display


public void setDensityDpi(int densityDpi) {
    if (isJB()) {
      this.densityDpi = densityDpi;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.logicalDensityDpi = densityDpi);
    }
  }

public void setDensityDpi ( int densityDpi ) { if ( isJB ( ) ) { this . densityDpi = densityDpi ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . logicalDensityDpi = densityDpi ) ; } }

Changes the density for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.


public void setXdpi(float xdpi) {
    if (isJB()) {
      this.xdpi = xdpi;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.physicalXDpi = xdpi);
    }
  }

public void setXdpi ( float xdpi ) { if ( isJB ( ) ) { this . xdpi = xdpi ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . physicalXDpi = xdpi ) ; } }

Changes the horizontal DPI for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

Changes the horizontal DPI for this display .


public void setYdpi(float ydpi) {
    if (isJB()) {
      this.ydpi = ydpi;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.physicalYDpi = ydpi);
    }
  }

public void setYdpi ( float ydpi ) { if ( isJB ( ) ) { this . ydpi = ydpi ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . physicalYDpi = ydpi ) ; } }

Changes the vertical DPI for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

Changes the vertical DPI for this display .


public void setName(String name) {
    if (isJB()) {
      this.name = name;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.name = name);
    }
  }

public void setName ( String name ) { if ( isJB ( ) ) { this . name = name ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . name = name ) ; } }

Changes the name for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.


public void setFlags(int flags) {
    reflector(_Display_.class, realObject).setFlags(flags);

    if (!isJB()) {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.flags = flags);
    }
  }

public void setFlags ( int flags ) { reflector ( _Display_ . class , realObject ) . setFlags ( flags ) ; if ( ! isJB ( ) ) { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . flags = flags ) ; } }

Changes the flags for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.


public void setWidth(int width) {
    if (isJB()) {
      this.width = width;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.appWidth = width);
    }
  }

public void setWidth ( int width ) { if ( isJB ( ) ) { this . width = width ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . appWidth = width ) ; } }

Changes the width available to the application for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

@param width the new width in pixels

Changes the width available to the application for this display .


public void setHeight(int height) {
    if (isJB()) {
      this.height = height;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.appHeight = height);
    }
  }

public void setHeight ( int height ) { if ( isJB ( ) ) { this . height = height ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . appHeight = height ) ; } }

Changes the height available to the application for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

@param height new height in pixels

Changes the height available to the application for this display .


public void setRealWidth(int width) {
    if (isJB()) {
      this.realWidth = width;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.logicalWidth = width);
    }
  }

public void setRealWidth ( int width ) { if ( isJB ( ) ) { this . realWidth = width ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . logicalWidth = width ) ; } }

Changes the simulated physical width for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

@param width the new width in pixels

Changes the simulated physical width for this display .


public void setRealHeight(int height) {
    if (isJB()) {
      this.realHeight = height;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.logicalHeight = height);
    }
  }

public void setRealHeight ( int height ) { if ( isJB ( ) ) { this . realHeight = height ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . logicalHeight = height ) ; } }

Changes the simulated physical height for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

@param height the new height in pixels

Changes the simulated physical height for this display .


public void setRotation(int rotation) {
    if (isJB()) {
      this.rotation = rotation;
    } else {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.rotation = rotation);
    }
  }

public void setRotation ( int rotation ) { if ( isJB ( ) ) { this . rotation = rotation ; } else { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . rotation = rotation ) ; } }

Changes the rotation for this display.

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

@param rotation one of {@link Surface#ROTATION_0}, {@link Surface#ROTATION_90},
{@link Surface#ROTATION_180}, {@link Surface#ROTATION_270}


public void setState(int state) {
    if (!isJB()) {
      ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
          di -> di.state = state);
    }
  }

public void setState ( int state ) { if ( ! isJB ( ) ) { ShadowDisplayManager . changeDisplay ( realObject . getDisplayId ( ) , di -> di . state = state ) ; } }

Changes the simulated state for this display, such as whether it is on or off

Any registered {@link android.hardware.display.DisplayManager.DisplayListener}s will be
notified of the change.

@param state the new state: one of {@link Display#STATE_OFF}, {@link Display#STATE_ON},
{@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND}, or
{@link Display#STATE_UNKNOWN}.

Changes the simulated state for this display such as whether it is on or off


protected void releaseConnection() {
    // Release the connection through the ManagedConnection instead of the
    // ConnectionManager directly.  This lets the connection control how
    // it is released.
    try {
      managedConn.releaseConnection();
    } catch(IOException ignored) {
      this.log.debug("IOException releasing connection", ignored);
    }
    managedConn = null;
  }

Returns the connection back to the connection manager
and prepares for retrieving a new connection during
the next request.

Returns the connection back to the connection manager and prepares for retrieving a new connection during the next request .


protected void establishRoute(HttpRoute route, HttpContext context)
    throws HttpException, IOException {

    HttpRouteDirector rowdy = new BasicRouteDirector();
    int step;
    do {
      HttpRoute fact = managedConn.getRoute();
      step = rowdy.nextStep(route, fact);

      switch (step) {

      case HttpRouteDirector.CONNECT_TARGET:
      case HttpRouteDirector.CONNECT_PROXY:
        managedConn.open(route, context, this.params);
        break;

      case HttpRouteDirector.TUNNEL_TARGET: {
        boolean secure = createTunnelToTarget(route, context);
        this.log.debug("Tunnel to target created.");
        managedConn.tunnelTarget(secure, this.params);
      }   break;

      case HttpRouteDirector.TUNNEL_PROXY: {
        // The most simple example for this case is a proxy chain
        // of two proxies, where P1 must be tunnelled to P2.
        // route: Source -> P1 -> P2 -> Target (3 hops)
        // fact:  Source -> P1 -> Target       (2 hops)
        final int hop = fact.getHopCount()-1; // the hop to establish
        boolean secure = createTunnelToProxy(route, hop, context);
        this.log.debug("Tunnel to proxy created.");
        managedConn.tunnelProxy(route.getHopTarget(hop),
                    secure, this.params);
      }   break;

      case HttpRouteDirector.LAYER_PROTOCOL:
        managedConn.layerProtocol(context, this.params);
        break;

      case HttpRouteDirector.UNREACHABLE:
        throw new IllegalStateException
          ("Unable to establish route." +
           "\nplanned = " + route +
           "\ncurrent = " + fact);

      case HttpRouteDirector.COMPLETE:
        // do nothing
        break;

      default:
        throw new IllegalStateException
          ("Unknown step indicator "+step+" from RouteDirector.");
      } // switch

    } while (step > HttpRouteDirector.COMPLETE);

  }

Establishes the target route.

@param route     the route to establish
@param context   the context for the request execution

@throws HttpException    in case of a problem
@throws IOException      in case of an IO problem


@Override
  protected String getCommonSuperClass(final String type1, final String type2) {
    try {
      ClassNode info1 = typeInfo(type1);
      ClassNode info2 = typeInfo(type2);
      if ((info1.access & Opcodes.ACC_INTERFACE) != 0) {
        if (typeImplements(type2, info2, type1)) {
          return type1;
        }
        if ((info2.access & Opcodes.ACC_INTERFACE) != 0) {
          if (typeImplements(type1, info1, type2)) {
            return type2;
          }
        }
        return "java/lang/Object";
      }
      if ((info2.access & Opcodes.ACC_INTERFACE) != 0) {
        if (typeImplements(type1, info1, type2)) {
          return type2;
        } else {
          return "java/lang/Object";
        }
      }
      String b1 = typeAncestors(type1, info1);
      String b2 = typeAncestors(type2, info2);
      String result = "java/lang/Object";
      int end1 = b1.length();
      int end2 = b2.length();
      while (true) {
        int start1 = b1.lastIndexOf(';', end1 - 1);
        int start2 = b2.lastIndexOf(';', end2 - 1);
        if (start1 != -1 && start2 != -1
            && end1 - start1 == end2 - start2) {
          String p1 = b1.substring(start1 + 1, end1);
          String p2 = b2.substring(start2 + 1, end2);
          if (p1.equals(p2)) {
            result = p1;
            end1 = start1;
            end2 = start2;
          } else {
            return result;
          }
        } else {
          return result;
        }
      }
    } catch (ClassNotFoundException e) {
      return "java/lang/Object"; // Handle classes that may be obfuscated
    }
  }

Returns the common super type of the two given types without actually loading
the classes in the ClassLoader.

Returns the common super type of the two given types without actually loading the classes in the ClassLoader .


public String qualify(String value) {
    if (value == null) return null;
    if (AttributeResource.isResourceReference(value)) {
      return "@" + ResName.qualifyResourceName(value.trim().substring(1).replace("+", ""), packageName, "attr");
    } else if (AttributeResource.isStyleReference(value)) {
      return "?" + ResName.qualifyResourceName(value.trim().substring(1), packageName, "attr");
    } else {
      return StringResources.processStringResources(value);
    }
  }

public String qualify ( String value ) { if ( value == null ) return null ; if ( AttributeResource . isResourceReference ( value ) ) { return "@" + ResName . qualifyResourceName ( value . trim ( ) . substring ( 1 ) . replace ( "+" , "" ) , packageName , "attr" ) ; } else if ( AttributeResource . isStyleReference ( value ) ) { return "?" + ResName . qualifyResourceName ( value . trim ( ) . substring ( 1 ) , packageName , "attr" ) ; } else { return StringResources . processStringResources ( value ) ; } }


int navigateToNextNode(Node node)
      throws XmlPullParserException {
    Node nextNode = node.getNextSibling();
    if (nextNode != null) {
      // Move to the next siblings
      return processNextNodeType(nextNode);
    } else {
      // Goes back to the parent
      if (document.getDocumentElement().equals(node)) {
        currentNode = null;
        return END_DOCUMENT;
      }
      currentNode = node.getParentNode();
      return END_TAG;
    }
  }

int
navigateToNextNode
(
Node
node
)
throws
XmlPullParserException
{
Node
nextNode
=
node
.
getNextSibling
(
)
;
if
(
nextNode
!=
)
{
// Move to the next siblings
return
processNextNodeType
(
nextNode
)
;
}
else
{
// Goes back to the parent
if
(
document
.
getDocumentElement
(
)
.
equals
(
node
)
)
{
currentNode
=
;
return
END_DOCUMENT
;
}
currentNode
=
node
.
getParentNode
(
)
;
return
END_TAG
;
}
}

Navigate to the next node after a node and all of his
children have been explored.

If the node has unexplored siblings navigate to the
next sibling. Otherwise return to its parent.

@param node the node which was just explored.
@return {@link XmlPullParserException#START_TAG} if the given
node has siblings, {@link XmlPullParserException#END_TAG}
if the node has no unexplored siblings or
{@link XmlPullParserException#END_DOCUMENT} if the explored
was the root document.
@throws XmlPullParserException if the parser fails to
parse the next node.

Navigate to the next node after a node and all of his children have been explored .


private static boolean isAndroidSupportedFeature(String name) {
    if (name == null) {
      return false;
    }
    for (String feature : AVAILABLE_FEATURES) {
      if (feature.equals(name)) {
        return true;
      }
    }
    return false;
  }

private static boolean isAndroidSupportedFeature ( String name ) { if ( name == null ) { return false ; } for ( String feature : AVAILABLE_FEATURES ) { if ( feature . equals ( name ) ) { return true ; } } return false ; }

Tell is a given feature is supported by android.

@param name Feature name.
@return True if the feature is supported.

Tell is a given feature is supported by android .


int add(
      Asset asset, Asset idmapAsset, final int cookie, boolean copyData,
      boolean appAsLib, boolean isSystemAsset) {
    final byte[] data = asset.getBuffer(true);
    if (data == NULL) {
      ALOGW("Unable to get buffer of resource asset file");
      return UNKNOWN_ERROR;
    }

    int idmapSize = 0;
    Object idmapData = NULL;
    if (idmapAsset != NULL) {
      idmapData = idmapAsset.getBuffer(true);
      if (idmapData == NULL) {
        ALOGW("Unable to get buffer of idmap asset file");
        return UNKNOWN_ERROR;
      }
      idmapSize = (int) idmapAsset.getLength();
    }

    return addInternal(data, (int) asset.getLength(),
        idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset);
  }

bool appAsLib=false, bool isSystemAsset=false);

bool appAsLib = false bool isSystemAsset = false ) ;


public static String getQualifiers(Configuration configuration, DisplayMetrics displayMetrics) {
    return ConfigurationV25.resourceQualifierString(configuration, displayMetrics);
  }

public static String getQualifiers ( Configuration configuration , DisplayMetrics displayMetrics ) { return ConfigurationV25 . resourceQualifierString ( configuration , displayMetrics ) ; }

Returns a qualifier string describing the given configuration and display metrics.

@param configuration the configuration.
@param displayMetrics the display metrics.
@return a qualifier string as described (https://developer.android.com/guide/topics/resources/providing-resources.html#QualifierRules)[here].

Returns a qualifier string describing the given configuration and display metrics .


public static void setQualifiers(String newQualifiers) {
    Configuration configuration;
    DisplayMetrics displayMetrics = new DisplayMetrics();
    if (newQualifiers.startsWith("+")) {
      configuration = new Configuration(Resources.getSystem().getConfiguration());
      displayMetrics.setTo(Resources.getSystem().getDisplayMetrics());
    } else {
      configuration = new Configuration();
    }
    Bootstrap.applyQualifiers(newQualifiers, getApiLevel(), configuration, displayMetrics);

    Resources systemResources = Resources.getSystem();
    systemResources.updateConfiguration(configuration, displayMetrics);

    if (application != null) {
      application.getResources().updateConfiguration(configuration, displayMetrics);
    }
  }

public static void setQualifiers ( String newQualifiers ) { Configuration configuration ; DisplayMetrics displayMetrics = new DisplayMetrics ( ) ; if ( newQualifiers . startsWith ( "+" ) ) { configuration = new Configuration ( Resources . getSystem ( ) . getConfiguration ( ) ) ; displayMetrics . setTo ( Resources . getSystem ( ) . getDisplayMetrics ( ) ) ; } else { configuration = new Configuration ( ) ; } Bootstrap . applyQualifiers ( newQualifiers , getApiLevel ( ) , configuration , displayMetrics ) ; Resources systemResources = Resources . getSystem ( ) ; systemResources . updateConfiguration ( configuration , displayMetrics ) ; if ( application != null ) { application . getResources ( ) . updateConfiguration ( configuration , displayMetrics ) ; } }

Overrides the current device configuration.

If `newQualifiers` starts with a plus (`+`), the prior configuration is used as the base
configuration, with the given changes applied additively. Otherwise, default values are used
for unspecified properties, as described [here](http://robolectric.org/device-configuration/).

@param newQualifiers the qualifiers to apply

Overrides the current device configuration .


public static String buildString(char[] data) {
    int count = 0;
    for (count=0; count < data.length; count++) {
      if (data[count] == 0) {
        break;
      }
    }
    return new String(data, 0, count);
  }

public static String buildString ( char [ ] data ) { int count = 0 ; for ( count = 0 ; count < data . length ; count ++ ) { if ( data [ count ] == 0 ) { break ; } } return new String ( data , 0 , count ) ; }

Builds a string from a null-terminated char data.

Builds a string from a null - terminated char data .


public static <S> ServiceFinder<S> load(Class<S> service,
      ClassLoader loader)
  {
    return new ServiceFinder<>(service, loader);
  }

public static < S > ServiceFinder < S > load ( Class < S > service , ClassLoader loader ) { return new ServiceFinder <> ( service , loader ) ; }

Creates a new service loader for the given service type and class
loader.

@param  <S> the class of the service type

@param  service
The interface or abstract class representing the service

@param  loader
The class loader to be used to load provider-configuration files
and provider classes, or <tt>null</tt> if the system class
loader (or, failing that, the bootstrap class loader) is to be
used

@return A new service loader

Creates a new service loader for the given service type and class loader .


public static <S> ServiceFinder<S> loadInstalled(Class<S> service) {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    ClassLoader prev = null;
    while (cl != null) {
      prev = cl;
      cl = cl.getParent();
    }
    return load(service, prev);
  }

public static < S > ServiceFinder < S > loadInstalled ( Class < S > service ) { ClassLoader cl = ClassLoader . getSystemClassLoader ( ) ; ClassLoader prev = null ; while ( cl != null ) { prev = cl ; cl = cl . getParent ( ) ; } return load ( service , prev ) ; }

Creates a new service loader for the given service type, using the
extension class loader.

 This convenience method simply locates the extension class loader,
call it <tt>extClassLoader</tt>, and then returns

ServiceFinder.load(service, extClassLoader)

 If the extension class loader cannot be found then the system class
loader is used; if there is no system class loader then the bootstrap
class loader is used.

 This method is intended for use when only installed providers are
desired.  The resulting service will only find and load providers that
have been installed into the current Java virtual machine; providers on
the application's class path will be ignored.

@param  <S> the class of the service type

@param  service
The interface or abstract class representing the service

@return A new service loader

Creates a new service loader for the given service type using the extension class loader .


public static <S> S loadFromSystemProperty(final Class<S> service) {
    try {
      final String className = System.getProperty(service.getName());
      if (className != null) {
        Class<?> c = ClassLoader.getSystemClassLoader().loadClass(className);
        return (S) c.newInstance();
      }
      return null;
    } catch (Exception e) {
      throw new Error(e);
    }
  }

public static < S > S loadFromSystemProperty ( final Class < S > service ) { try { final String className = System . getProperty ( service . getName ( ) ) ; if ( className != null ) { Class < ? > c = ClassLoader . getSystemClassLoader ( ) . loadClass ( className ) ; return ( S ) c . newInstance ( ) ; } return null ; } catch ( Exception e ) { throw new Error ( e ) ; } }

Internal API to support built-in SPIs that check a system property first.
Returns an instance specified by a property with the class' binary name, or null if
no such property is set.
@hide

Internal API to support built - in SPIs that check a system property first . Returns an instance specified by a property with the class binary name or null if no such property is set .


public boolean hasPermissionForPackage(UsbDevice device, String packageName) {
    List<UsbDevice> usbDevices = grantedPermissions.get(packageName);
    return usbDevices != null && usbDevices.contains(device);
  }

public boolean hasPermissionForPackage ( UsbDevice device , String packageName ) { List < UsbDevice > usbDevices = grantedPermissions . get ( packageName ) ; return usbDevices != null && usbDevices . contains ( device ) ; }

Returns true if the given package has permission to access the device.

Returns true if the given package has permission to access the device .


public void revokePermission(UsbDevice device, String packageName) {
    List<UsbDevice> usbDevices = grantedPermissions.get(packageName);
    if (usbDevices != null) {
      usbDevices.remove(device);
    }
  }

public void revokePermission ( UsbDevice device , String packageName ) { List < UsbDevice > usbDevices = grantedPermissions . get ( packageName ) ; if ( usbDevices != null ) { usbDevices . remove ( device ) ; } }

Revokes permission to a USB device granted to a package. This method does nothing if the
package doesn't have permission to access the device.

Revokes permission to a USB device granted to a package . This method does nothing if the package doesn t have permission to access the device .


public void addOrUpdateUsbDevice(UsbDevice usbDevice, boolean hasPermission) {
    Preconditions.checkNotNull(usbDevice);
    Preconditions.checkNotNull(usbDevice.getDeviceName());
    usbDevices.put(usbDevice.getDeviceName(), usbDevice);
    if (hasPermission) {
      grantPermission(usbDevice);
    } else {
      revokePermission(usbDevice, RuntimeEnvironment.application.getPackageName());
    }
  }

public void addOrUpdateUsbDevice ( UsbDevice usbDevice , boolean hasPermission ) { Preconditions . checkNotNull ( usbDevice ) ; Preconditions . checkNotNull ( usbDevice . getDeviceName ( ) ) ; usbDevices . put ( usbDevice . getDeviceName ( ) , usbDevice ) ; if ( hasPermission ) { grantPermission ( usbDevice ) ; } else { revokePermission ( usbDevice , RuntimeEnvironment . application . getPackageName ( ) ) ; } }

Adds a USB device into available USB devices map with permission value. If the USB device
already exists, updates the USB device with new permission value.

Adds a USB device into available USB devices map with permission value . If the USB device already exists updates the USB device with new permission value .


public void removeUsbDevice(UsbDevice usbDevice) {
    Preconditions.checkNotNull(usbDevice);
    usbDevices.remove(usbDevice.getDeviceName());
    revokePermission(usbDevice, RuntimeEnvironment.application.getPackageName());
  }

public void removeUsbDevice ( UsbDevice usbDevice ) { Preconditions . checkNotNull ( usbDevice ) ; usbDevices . remove ( usbDevice . getDeviceName ( ) ) ; revokePermission ( usbDevice , RuntimeEnvironment . application . getPackageName ( ) ) ; }

Removes a USB device from available USB devices map.

Removes a USB device from available USB devices map .


public void addPort(String portId) {
    if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.Q) {
      usbPorts.put(
          (UsbPort) createUsbPort(realUsbManager, portId, UsbPortStatus.MODE_DUAL),
          (UsbPortStatus) createUsbPortStatus(
              UsbPortStatus.MODE_DUAL,
              UsbPortStatus.POWER_ROLE_SINK,
              UsbPortStatus.DATA_ROLE_DEVICE,
              0));
      return;
    }

    usbPorts.put(
        callConstructor(UsbPort.class,
            from(String.class, portId),
            from(int.class, getStaticField(UsbPort.class, "MODE_DUAL"))),
        (UsbPortStatus) createUsbPortStatus(
            getStaticField(UsbPort.class, "MODE_DUAL"),
            getStaticField(UsbPort.class, "POWER_ROLE_SINK"),
            getStaticField(UsbPort.class, "DATA_ROLE_DEVICE"),
            0));
  }

public void addPort ( String portId ) { if ( RuntimeEnvironment . getApiLevel ( ) >= Build . VERSION_CODES . Q ) { usbPorts . put ( ( UsbPort ) createUsbPort ( realUsbManager , portId , UsbPortStatus . MODE_DUAL ) , ( UsbPortStatus ) createUsbPortStatus ( UsbPortStatus . MODE_DUAL , UsbPortStatus . POWER_ROLE_SINK , UsbPortStatus . DATA_ROLE_DEVICE , 0 ) ) ; return ; } usbPorts . put ( callConstructor ( UsbPort . class , from ( String . class , portId ) , from ( int . class , getStaticField ( UsbPort . class , "MODE_DUAL" ) ) ) , ( UsbPortStatus ) createUsbPortStatus ( getStaticField ( UsbPort . class , "MODE_DUAL" ) , getStaticField ( UsbPort . class , "POWER_ROLE_SINK" ) , getStaticField ( UsbPort . class , "DATA_ROLE_DEVICE" ) , 0 ) ) ; }


@Implementation
  protected ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
    try {
      File tmpUsbDir =
          RuntimeEnvironment.getTempDirectory().createIfNotExists("usb-accessory").toFile();
      return ParcelFileDescriptor.open(
          new File(tmpUsbDir, "usb-accessory-file"), ParcelFileDescriptor.MODE_READ_WRITE);
    } catch (FileNotFoundException error) {
      throw new RuntimeException("Error shadowing openAccessory", error);
    }
  }

@
Implementation
protected
ParcelFileDescriptor
openAccessory
(
UsbAccessory
accessory
)
{
try
{
File
tmpUsbDir
=
RuntimeEnvironment
.
getTempDirectory
(
)
.
createIfNotExists
(
"usb-accessory"
)
.
toFile
(
)
;
return
ParcelFileDescriptor
.
open
(
new
File
(
tmpUsbDir
,
"usb-accessory-file"
)
,
ParcelFileDescriptor
.
MODE_READ_WRITE
)
;
}
catch
(
FileNotFoundException
error
)
{
throw
new
RuntimeException
(
"Error shadowing openAccessory"
,
error
)
;
}
}

Opens a file descriptor from a temporary file.

Opens a file descriptor from a temporary file .


void addData(String tag, long timestamp, byte[] data) {
    entries.put(timestamp, new DropBoxManager.Entry(tag, timestamp, data, DropBoxManager.IS_TEXT));
  }

void addData ( String tag , long timestamp , byte [ ] data ) { entries . put ( timestamp , new DropBoxManager . Entry ( tag , timestamp , data , DropBoxManager . IS_TEXT ) ) ; }

Adds entry to the DropboxManager with the flag indicating data is text.

The existing {@link DropBoxManager#addData}, {@link DropBoxManager#addFile}, and {@link
DropBoxManager#addText} methods in DropBoxManager are not shadowed. This method is a
convenience for quickly adding multiple historical entries. The entries can be added in any
order since this shadow will sort the entries by the specified timestamp.

The flag will be set to {@link DropBoxManager#IS_TEXT} so that {@link
DropBoxManager.Entry#getText} can be used.

@param tag can be any arbitrary string
@param timestamp is an arbitrary timestamp that must be unique from all other entries
@param data must not be null

Adds entry to the DropboxManager with the flag indicating data is text .


public MediaItem createMediaItem(String parentId, String mediaId, String title, int flag) {
    final MediaMetadataCompat metadataCompat =
        new MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, mediaId)
            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, Uri.parse(mediaId).toString())
            .build();
    final MediaItem mediaItem = new MediaItem(metadataCompat.getDescription(), flag);
    mediaItems.put(mediaId, mediaItem);

    // If this MediaItem is the child of a MediaItem that has already been created. This applies to
    // all MediaItems except the root.
    if (parentId != null) {
      final MediaItem parentItem = mediaItems.get(parentId);
      List<MediaItem> children = mediaItemChildren.get(parentItem);
      if (children == null) {
        children = new ArrayList<>();
        mediaItemChildren.put(parentItem, children);
      }
      children.add(mediaItem);
    }

    return mediaItem;
  }

Creates a MediaItem and returns it.

@param parentId the id of the parent MediaItem. If the MediaItem to be created will be the
root, parentId should be null.
@param mediaId the id of the MediaItem to be created.
@param title the title of the MediaItem to be created.
@param flag says if the MediaItem to be created is browsable and/or playable.
@return the newly created MediaItem.


public static <T> T createDeepProxy(Class<T> clazz) {
    return (T)
        Proxy.newProxyInstance(
            clazz.getClassLoader(),
            new Class[] {clazz},
            new InvocationHandler() {
              @Override
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (PRIMITIVE_RETURN_VALUES.containsKey(method.getReturnType().getName())) {
                  return PRIMITIVE_RETURN_VALUES.get(method.getReturnType().getName());
                } else if (method.getReturnType().isInterface()) {
                  return createDeepProxy(method.getReturnType());
                } else {
                  return null;
                }
              }
            });
  }

public static < T > T createDeepProxy ( Class < T > clazz ) { return ( T ) Proxy . newProxyInstance ( clazz . getClassLoader ( ) , new Class [ ] { clazz } , new InvocationHandler ( ) { @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( PRIMITIVE_RETURN_VALUES . containsKey ( method . getReturnType ( ) . getName ( ) ) ) { return PRIMITIVE_RETURN_VALUES . get ( method . getReturnType ( ) . getName ( ) ) ; } else if ( method . getReturnType ( ) . isInterface ( ) ) { return createDeepProxy ( method . getReturnType ( ) ) ; } else { return null ; } } } ) ; }

Create a proxy for the given class which returns other deep proxies from all it's methods.

The returned object will be an instance of the given class, but all methods will return
either the "default" value for primitives, or another deep proxy for non-primitive types.

This should be used rarely, for cases where we need to create deep proxies in order not
to crash. The inner proxies are impossible to configure, so there is no way to create
meaningful behavior from a deep proxy. It serves mainly to prevent Null Pointer Exceptions.
@param clazz the class to provide a proxy instance of.
@return a new "Deep Proxy" instance of the given class.

Create a proxy for the given class which returns other deep proxies from all it s methods .


@SuppressWarnings("unchecked")
  public static <R> R getField(final Object object, final String fieldName) {
    try {
      return traverseClassHierarchy(object.getClass(), NoSuchFieldException.class, new InsideTraversal<R>() {
        @Override
        public R run(Class<?> traversalClass) throws Exception {
          Field field = traversalClass.getDeclaredField(fieldName);
          field.setAccessible(true);
          return (R) field.get(object);
        }
      });
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

@ SuppressWarnings ( "unchecked" ) public static < R > R getField ( final Object object , final String fieldName ) { try { return traverseClassHierarchy ( object . getClass ( ) , NoSuchFieldException . class , new InsideTraversal < R > ( ) { @ Override public R run ( Class < ? > traversalClass ) throws Exception { Field field = traversalClass . getDeclaredField ( fieldName ) ; field . setAccessible ( true ) ; return ( R ) field . get ( object ) ; } } ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }

Reflectively get the value of a field.

@param object Target object.
@param fieldName The field name.
@param <R> The return type.
@return Value of the field on the object.


public static <R> R callInstanceMethod(final Object instance, final String methodName, ClassParameter<?>... classParameters) {
    try {
      final Class<?>[] classes = ClassParameter.getClasses(classParameters);
      final Object[] values = ClassParameter.getValues(classParameters);

      return traverseClassHierarchy(instance.getClass(), NoSuchMethodException.class, new InsideTraversal<R>() {
        @Override
        @SuppressWarnings("unchecked")
        public R run(Class<?> traversalClass) throws Exception {
          Method declaredMethod = traversalClass.getDeclaredMethod(methodName, classes);
          declaredMethod.setAccessible(true);
          return (R) declaredMethod.invoke(instance, values);
        }
      });
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof RuntimeException) {
        throw (RuntimeException) e.getTargetException();
      }
      if (e.getTargetException() instanceof Error) {
        throw (Error) e.getTargetException();
      }
      throw new RuntimeException(e.getTargetException());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

public static < R > R callInstanceMethod ( final Object instance , final String methodName , ClassParameter < ? > ... classParameters ) { try { final Class < ? > [ ] classes = ClassParameter . getClasses ( classParameters ) ; final Object [ ] values = ClassParameter . getValues ( classParameters ) ; return traverseClassHierarchy ( instance . getClass ( ) , NoSuchMethodException . class , new InsideTraversal < R > ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public R run ( Class < ? > traversalClass ) throws Exception { Method declaredMethod = traversalClass . getDeclaredMethod ( methodName , classes ) ; declaredMethod . setAccessible ( true ) ; return ( R ) declaredMethod . invoke ( instance , values ) ; } } ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } if ( e . getTargetException ( ) instanceof Error ) { throw ( Error ) e . getTargetException ( ) ; } throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }

Reflectively call an instance method on an object.

@param instance Target object.
@param methodName The method name to call.
@param classParameters Array of parameter types and values.
@param <R> The return type.
@return The return value of the method.

Reflectively call an instance method on an object .


public static <R> R callInstanceMethod(Class<?> cl, final Object instance, final String methodName, ClassParameter<?>... classParameters) {
    try {
      final Class<?>[] classes = ClassParameter.getClasses(classParameters);
      final Object[] values = ClassParameter.getValues(classParameters);

      Method method = cl.getDeclaredMethod(methodName, classes);
      method.setAccessible(true);
      if (Modifier.isStatic(method.getModifiers())) {
        throw new IllegalArgumentException(method + " is static");
      }
      return (R) method.invoke(instance, values);
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof RuntimeException) {
        throw (RuntimeException) e.getTargetException();
      }
      if (e.getTargetException() instanceof Error) {
        throw (Error) e.getTargetException();
      }
      throw new RuntimeException(e.getTargetException());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

public
static
<
R
>
R
callInstanceMethod
(
Class
<
>
cl
,
final
Object
instance
,
final
String
methodName
,
ClassParameter
<
>
...
classParameters
)
{
try
{
final
Class
<
>
[
]
classes
=
ClassParameter
.
getClasses
(
classParameters
)
;
final
Object
[
]
values
=
ClassParameter
.
getValues
(
classParameters
)
;
Method
method
=
cl
.
getDeclaredMethod
(
methodName
,
classes
)
;
method
.
setAccessible
(
true
)
;
if
(
Modifier
.
isStatic
(
method
.
getModifiers
(
)
)
)
{
throw
new
IllegalArgumentException
(
method
+
" is static"
)
;
}
return
(
R
)
method
.
invoke
(
instance
,
values
)
;
}
catch
(
InvocationTargetException
e
)
{
if
(
e
.
getTargetException
(
)
instanceof
RuntimeException
)
{
throw
(
RuntimeException
)
e
.
getTargetException
(
)
;
}
if
(
e
.
getTargetException
(
)
instanceof
Error
)
{
throw
(
Error
)
e
.
getTargetException
(
)
;
}
throw
new
RuntimeException
(
e
.
getTargetException
(
)
)
;
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
e
)
;
}
}

Reflectively call an instance method on an object on a specific class.

@param cl The class.
@param instance Target object.
@param methodName The method name to call.
@param classParameters Array of parameter types and values.
@param <R> The return type.
@return The return value of the method.

Reflectively call an instance method on an object on a specific class .


public static <R> R callStaticMethod(
      ClassLoader classLoader,
      String fullyQualifiedClassName,
      String methodName,
      ClassParameter<?>... classParameters) {
    Class<?> clazz = loadClass(classLoader, fullyQualifiedClassName);
    return callStaticMethod(clazz, methodName, classParameters);
  }

public static < R > R callStaticMethod ( ClassLoader classLoader , String fullyQualifiedClassName , String methodName , ClassParameter < ? > ... classParameters ) { Class < ? > clazz = loadClass ( classLoader , fullyQualifiedClassName ) ; return callStaticMethod ( clazz , methodName , classParameters ) ; }

Helper method for calling a static method using a class from a custom class loader

@param classLoader
@param fullyQualifiedClassName
@param methodName
@param classParameters
@param <R>
@return


@SuppressWarnings("unchecked")
  public static <R> R callStaticMethod(Class<?> clazz, String methodName, ClassParameter<?>... classParameters) {
    try {
      Class<?>[] classes = ClassParameter.getClasses(classParameters);
      Object[] values = ClassParameter.getValues(classParameters);

      Method method = clazz.getDeclaredMethod(methodName, classes);
      method.setAccessible(true);
      if (!Modifier.isStatic(method.getModifiers())) {
        throw new IllegalArgumentException(method + " is not static");
      }
      return (R) method.invoke(null, values);
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof RuntimeException) {
        throw (RuntimeException) e.getTargetException();
      }
      if (e.getTargetException() instanceof Error) {
        throw (Error) e.getTargetException();
      }
      throw new RuntimeException(e.getTargetException());
    } catch (NoSuchMethodException e) {
      throw new RuntimeException("no such method " + clazz + "." + methodName, e);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

@
SuppressWarnings
(
"unchecked"
)
public
static
<
R
>
R
callStaticMethod
(
Class
<
>
clazz
,
String
methodName
,
ClassParameter
<
>
...
classParameters
)
{
try
{
Class
<
>
[
]
classes
=
ClassParameter
.
getClasses
(
classParameters
)
;
Object
[
]
values
=
ClassParameter
.
getValues
(
classParameters
)
;
Method
method
=
clazz
.
getDeclaredMethod
(
methodName
,
classes
)
;
method
.
setAccessible
(
true
)
;
if
(
!
Modifier
.
isStatic
(
method
.
getModifiers
(
)
)
)
{
throw
new
IllegalArgumentException
(
method
+
" is not static"
)
;
}
return
(
R
)
method
.
invoke
(
,
values
)
;
}
catch
(
InvocationTargetException
e
)
{
if
(
e
.
getTargetException
(
)
instanceof
RuntimeException
)
{
throw
(
RuntimeException
)
e
.
getTargetException
(
)
;
}
if
(
e
.
getTargetException
(
)
instanceof
Error
)
{
throw
(
Error
)
e
.
getTargetException
(
)
;
}
throw
new
RuntimeException
(
e
.
getTargetException
(
)
)
;
}
catch
(
NoSuchMethodException
e
)
{
throw
new
RuntimeException
(
"no such method "
+
clazz
+
"."
+
methodName
,
e
)
;
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
e
)
;
}
}

Reflectively call a static method on a class.

@param clazz Target class.
@param methodName The method name to call.
@param classParameters Array of parameter types and values.
@param <R> The return type.
@return The return value of the method.

Reflectively call a static method on a class .


public static <T> T newInstance(Class<T> cl) {
    try {
      return cl.getDeclaredConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException
        | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
  }

public static < T > T newInstance ( Class < T > cl ) { try { return cl . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } }

Create a new instance of a class

@param cl The class object.
@param <T> The class type.
@return New class instance.


public static <R> R callConstructor(Class<? extends R> clazz, ClassParameter<?>... classParameters) {
    try {
      final Class<?>[] classes = ClassParameter.getClasses(classParameters);
      final Object[] values = ClassParameter.getValues(classParameters);

      Constructor<? extends R> constructor = clazz.getDeclaredConstructor(classes);
      constructor.setAccessible(true);
      return constructor.newInstance(values);
    } catch (InstantiationException e) {
      throw new RuntimeException("error instantiating " + clazz.getName(), e);
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof RuntimeException) {
        throw (RuntimeException) e.getTargetException();
      }
      if (e.getTargetException() instanceof Error) {
        throw (Error) e.getTargetException();
      }
      throw new RuntimeException(e.getTargetException());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

public
static
<
R
>
R
callConstructor
(
Class
<
extends
R
>
clazz
,
ClassParameter
<
>
...
classParameters
)
{
try
{
final
Class
<
>
[
]
classes
=
ClassParameter
.
getClasses
(
classParameters
)
;
final
Object
[
]
values
=
ClassParameter
.
getValues
(
classParameters
)
;
Constructor
<
extends
R
>
constructor
=
clazz
.
getDeclaredConstructor
(
classes
)
;
constructor
.
setAccessible
(
true
)
;
return
constructor
.
newInstance
(
values
)
;
}
catch
(
InstantiationException
e
)
{
throw
new
RuntimeException
(
"error instantiating "
+
clazz
.
getName
(
)
,
e
)
;
}
catch
(
InvocationTargetException
e
)
{
if
(
e
.
getTargetException
(
)
instanceof
RuntimeException
)
{
throw
(
RuntimeException
)
e
.
getTargetException
(
)
;
}
if
(
e
.
getTargetException
(
)
instanceof
Error
)
{
throw
(
Error
)
e
.
getTargetException
(
)
;
}
throw
new
RuntimeException
(
e
.
getTargetException
(
)
)
;
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
e
)
;
}
}

Reflectively call the constructor of an object.

@param clazz Target class.
@param classParameters Array of parameter types and values.
@param <R> The return type.
@return The return value of the method.

Reflectively call the constructor of an object .


@Implementation(minSdk = P)
  protected void startRanging(
      RangingRequest request, Executor executor, RangingResultCallback callback) {
    if (!rangingResults.isEmpty()) {
      executor.execute(() -> callback.onRangingResults(this.rangingResults));
    } else {
      executor.execute(() -> callback.onRangingFailure(RangingResultCallback.STATUS_CODE_FAIL));
    }
  }

@ Implementation ( minSdk = P ) protected void startRanging ( RangingRequest request , Executor executor , RangingResultCallback callback ) { if ( ! rangingResults . isEmpty ( ) ) { executor . execute ( ( ) -> callback . onRangingResults ( this . rangingResults ) ) ; } else { executor . execute ( ( ) -> callback . onRangingFailure ( RangingResultCallback . STATUS_CODE_FAIL ) ) ; } }

If there are RangingResults set by the setRangeResults method of this shadow class, this method
will call the onRangingResults method of the callback on the executor thread and pass the list
of RangingResults. If there are no ranging results set, it will pass
RangingResultCallback.STATUS_CODE_FAIL to the onRangingFailure method of the callback, also
called on the executor thread.

If there are RangingResults set by the setRangeResults method of this shadow class this method will call the onRangingResults method of the callback on the executor thread and pass the list of RangingResults . If there are no ranging results set it will pass RangingResultCallback . STATUS_CODE_FAIL to the onRangingFailure method of the callback also called on the executor thread .


@Implementation
  public static Typeface getFontSync(FontRequest request) {
    return Typeface.create(request.getQuery(), Typeface.NORMAL);
  }

@ Implementation public static Typeface getFontSync ( FontRequest request ) { return Typeface . create ( request . getQuery ( ) , Typeface . NORMAL ) ; }


@Nonnull
  synchronized public PackageResourceTable getCompileTimeSdkResourceTable() {
    if (compiletimeSdkResourceTable == null) {
      ResourceTableFactory resourceTableFactory = new ResourceTableFactory();
      compiletimeSdkResourceTable = resourceTableFactory
          .newFrameworkResourceTable(new ResourcePath(android.R.class, null, null));
    }
    return compiletimeSdkResourceTable;
  }

@ Nonnull synchronized public PackageResourceTable getCompileTimeSdkResourceTable ( ) { if ( compiletimeSdkResourceTable == null ) { ResourceTableFactory resourceTableFactory = new ResourceTableFactory ( ) ; compiletimeSdkResourceTable = resourceTableFactory . newFrameworkResourceTable ( new ResourcePath ( android . R . class , null , null ) ) ; } return compiletimeSdkResourceTable ; }

Returns the ResourceTable for the compile time SDK.

Returns the ResourceTable for the compile time SDK .


@SuppressWarnings("UnusedDeclaration")
  @Deprecated
  public static void dump(View view) {
    ShadowView shadowView = Shadow.extract(view);
    shadowView.dump();
  }

@ SuppressWarnings ( "UnusedDeclaration" ) @ Deprecated public static void dump ( View view ) { ShadowView shadowView = Shadow . extract ( view ) ; shadowView . dump ( ) ; }

Emits an xml-like representation of the view to System.out.

@param view the view to dump.
@deprecated - Please use {@link androidx.test.espresso.util.HumanReadables#describe(View)}

Emits an xml - like representation of the view to System . out .


@SuppressWarnings("UnusedDeclaration")
  public static String innerText(View view) {
    ShadowView shadowView = Shadow.extract(view);
    return shadowView.innerText();
  }

@ SuppressWarnings ( "UnusedDeclaration" ) public static String innerText ( View view ) { ShadowView shadowView = Shadow . extract ( view ) ; return shadowView . innerText ( ) ; }

Returns the text contained within this view.

@param view the view to scan for text
@return Text contained within this view.

Returns the text contained within this view .


private List<Wrapper> getAppropriateWrappers(Intent intent, String receiverPermission) {
    broadcastIntents.add(intent);

    List<Wrapper> result = new ArrayList<>();

    List<Wrapper> copy = new ArrayList<>();
    copy.addAll(registeredReceivers);
    String intentClass =
        intent.getComponent() != null ? intent.getComponent().getClassName() : null;
    for (Wrapper wrapper : copy) {
      if ((hasMatchingPermission(wrapper.broadcastPermission, receiverPermission)
              && wrapper.intentFilter.matchAction(intent.getAction()))
          || (intentClass != null
              && intentClass.equals(wrapper.broadcastReceiver.getClass().getName()))) {
        final int match =
            wrapper.intentFilter.matchData(intent.getType(), intent.getScheme(), intent.getData());
        if (match != IntentFilter.NO_MATCH_DATA && match != IntentFilter.NO_MATCH_TYPE) {
          result.add(wrapper);
        }
      }
    }
    return result;
  }

private List < Wrapper > getAppropriateWrappers ( Intent intent , String receiverPermission ) { broadcastIntents . add ( intent ) ; List < Wrapper > result = new ArrayList <> ( ) ; List < Wrapper > copy = new ArrayList <> ( ) ; copy . addAll ( registeredReceivers ) ; String intentClass = intent . getComponent ( ) != null ? intent . getComponent ( ) . getClassName ( ) : null ; for ( Wrapper wrapper : copy ) { if ( ( hasMatchingPermission ( wrapper . broadcastPermission , receiverPermission ) && wrapper . intentFilter . matchAction ( intent . getAction ( ) ) ) || ( intentClass != null && intentClass . equals ( wrapper . broadcastReceiver . getClass ( ) . getName ( ) ) ) ) { final int match = wrapper . intentFilter . matchData ( intent . getType ( ) , intent . getScheme ( ) , intent . getData ( ) ) ; if ( match != IntentFilter . NO_MATCH_DATA && match != IntentFilter . NO_MATCH_TYPE ) { result . add ( wrapper ) ; } } } return result ; }

Returns the BroadcaseReceivers wrappers, matching intent's action and permissions.

Returns the BroadcaseReceivers wrappers matching intent s action and permissions .


private ListenableFuture<BroadcastResultHolder> postIntent(
      final Wrapper wrapper,
      final Intent intent,
      ListenableFuture<BroadcastResultHolder> oldResult,
      final AtomicBoolean abort,
      final Context context) {
    final Handler scheduler =
        (wrapper.scheduler != null) ? wrapper.scheduler : getMainHandler(context);
    return Futures.transformAsync(
        oldResult,
        new AsyncFunction<BroadcastResultHolder, BroadcastResultHolder>() {
          @Override
          public ListenableFuture<BroadcastResultHolder> apply(
              BroadcastResultHolder broadcastResultHolder) throws Exception {
            final BroadcastReceiver.PendingResult result =
                ShadowBroadcastPendingResult.create(
                    broadcastResultHolder.resultCode,
                    broadcastResultHolder.resultData,
                    broadcastResultHolder.resultExtras,
                    true /*ordered */);
            wrapper.broadcastReceiver.setPendingResult(result);
            scheduler.post(
                () -> {
                  ShadowBroadcastReceiver shadowBroadcastReceiver =
                      Shadow.extract(wrapper.broadcastReceiver);
                  shadowBroadcastReceiver.onReceive(context, intent, abort);
                });
            return BroadcastResultHolder.transform(result);
          }
        },
        directExecutor());
  }

private
ListenableFuture
<
BroadcastResultHolder
>
postIntent
(
final
Wrapper
wrapper
,
final
Intent
intent
,
ListenableFuture
<
BroadcastResultHolder
>
oldResult
,
final
AtomicBoolean
abort
,
final
Context
context
)
{
final
Handler
scheduler
=
(
wrapper
.
scheduler
!=
)
wrapper
.
scheduler
:
getMainHandler
(
context
)
;
return
Futures
.
transformAsync
(
oldResult
,
new
AsyncFunction
<
BroadcastResultHolder
,
BroadcastResultHolder
>
(
)
{
@
Override
public
ListenableFuture
<
BroadcastResultHolder
>
apply
(
BroadcastResultHolder
broadcastResultHolder
)
throws
Exception
{
final
BroadcastReceiver
.
PendingResult
result
=
ShadowBroadcastPendingResult
.
create
(
broadcastResultHolder
.
resultCode
,
broadcastResultHolder
.
resultData
,
broadcastResultHolder
.
resultExtras
,
true
/*ordered */
)
;
wrapper
.
broadcastReceiver
.
setPendingResult
(
result
)
;
scheduler
.
post
(
(
)
->
{
ShadowBroadcastReceiver
shadowBroadcastReceiver
=
Shadow
.
extract
(
wrapper
.
broadcastReceiver
)
;
shadowBroadcastReceiver
.
onReceive
(
context
,
intent
,
abort
)
;
}
)
;
return
BroadcastResultHolder
.
transform
(
result
)
;
}
}
,
directExecutor
(
)
)
;
}

Enforces that BroadcastReceivers invoked during an ordered broadcast run serially, passing
along their results.

Enforces that BroadcastReceivers invoked during an ordered broadcast run serially passing along their results .


@Implementation
  protected static void RGBToHSV(int red, int green, int blue, float hsv[]) {
    java.awt.Color.RGBtoHSB(red, green, blue, hsv);
    hsv[0] = hsv[0] * 360;
  }

@ Implementation protected static void RGBToHSV ( int red , int green , int blue , float hsv [ ] ) { java . awt . Color . RGBtoHSB ( red , green , blue , hsv ) ; hsv [ 0 ] = hsv [ 0 ] * 360 ; }

This is implemented in native code in the Android SDK.

<p>Since HSV == HSB then the implementation from {@link java.awt.Color} can be used, with a
small adjustment to the representation of the hue.

<p>{@link java.awt.Color} represents hue as 0..1 (where 1 == 100% == 360 degrees), while {@link
android.graphics.Color} represents hue as 0..360 degrees. The correct hue can be calculated by
multiplying with 360.

@param red Red component
@param green Green component
@param blue Blue component
@param hsv Array to store HSV components

This is implemented in native code in the Android SDK .


@Implementation(minSdk = JELLY_BEAN_MR2)
  protected static void beginSection(String sectionName) {
    if (Trace.isTagEnabled(TRACE_TAG_APP)) {
      if (crashOnIncorrectUsage) {
        if (sectionName.length() > MAX_SECTION_NAME_LEN) {
          throw new IllegalArgumentException("sectionName is too long");
        }
      } else if (sectionName == null) {
        Log.w(TAG, "Section name cannot be null");
        return;
      } else if (sectionName.length() > MAX_SECTION_NAME_LEN) {
        Log.w(TAG, "Section name is too long");
        return;
      }

      synchronized (lock) {
        currentSections.addFirst(sectionName);
      }
    }
  }

@
Implementation
(
minSdk
=
JELLY_BEAN_MR2
)
protected
static
void
beginSection
(
String
sectionName
)
{
if
(
Trace
.
isTagEnabled
(
TRACE_TAG_APP
)
)
{
if
(
crashOnIncorrectUsage
)
{
if
(
sectionName
.
length
(
)
>
MAX_SECTION_NAME_LEN
)
{
throw
new
IllegalArgumentException
(
"sectionName is too long"
)
;
}
}
else
if
(
sectionName
==
)
{
Log
.
w
(
TAG
,
"Section name cannot be null"
)
;
return
;
}
else
if
(
sectionName
.
length
(
)
>
MAX_SECTION_NAME_LEN
)
{
Log
.
w
(
TAG
,
"Section name is too long"
)
;
return
;
}
synchronized
(
lock
)
{
currentSections
.
addFirst
(
sectionName
)
;
}
}
}

Starts a new trace section with given name.

Starts a new trace section with given name .


@Implementation(minSdk = JELLY_BEAN_MR2)
  protected static void endSection() {
    if (Trace.isTagEnabled(TRACE_TAG_APP)) {
      synchronized (lock) {
        if (currentSections.isEmpty()) {
          Log.e(TAG, "Trying to end a trace section that was never started");
          return;
        }

        previousSections.offer(currentSections.removeFirst());
      }
    }
  }

Ends the most recent active trace section.

@throws {@link AssertionError} if called without any active trace section.

Ends the most recent active trace section .


@SuppressWarnings("unchecked")
  @Nonnull
  private synchronized <T> Provider<T> getProvider(final Key<T> key) {
    // Previously-gotten providers (including those from subinjectors) will already be present.
    return (Provider<T>) providers.computeIfAbsent(key, k -> {
      // @AutoFactory requests are always handled by the top-level injector.
      if (key.isAutoFactory()) {
        return memoized(new ScopeBuilderProvider<>(key.getDependencyClass()));
      }

      // Find a provider locally.
      return findLocalProvider(key);
    });
  }

Finds a provider for the given key.

Calls are guaranteed idempotent and non-blocking.


boolean create(String origFileName, int fd, long offset, int length,
      boolean readOnly)
  {
    this.mFileName = origFileName;
    this.fd = fd;
    this.mDataOffset = offset;
    this.readOnly = readOnly;
    return true;
  }

boolean create ( String origFileName , int fd , long offset , int length , boolean readOnly ) { this . mFileName = origFileName ; this . fd = fd ; this . mDataOffset = offset ; this . readOnly = readOnly ; return true ; }


public int runAll() {
    int numTasksRun = 0;
    if (Thread.currentThread().equals(executorThread)) {
      Logger.info("ignoring request to execute task - called from executor's own thread");
      return numTasksRun;
    }
    while (hasQueuedTasks()) {
      runNext();
      numTasksRun++;
    }
    return numTasksRun;
  }

Execute all posted tasks and block until they are complete.

@return the number of tasks executed

Execute all posted tasks and block until they are complete .


public boolean runNext() {
    if (!hasQueuedTasks()) {
      return false;
    }
    if (Thread.currentThread().equals(executorThread)) {
      Logger.info("ignoring request to execute task - called from executor's own thread");
      return false;
    }
    Runnable task = deferredTasks.poll();
    task.run();
    return true;
  }

Executes the next queued task.

Will be ignored if called from the executor service thread to prevent deadlocks.

@return true if task was run, false if queue was empty


@Implementation(minSdk = O)
  protected int requestAudioFocus(android.media.AudioFocusRequest audioFocusRequest) {
    lastAudioFocusRequest = new AudioFocusRequest(audioFocusRequest);
    return nextResponseValue;
  }

@ Implementation ( minSdk = O ) protected int requestAudioFocus ( android . media . AudioFocusRequest audioFocusRequest ) { lastAudioFocusRequest = new AudioFocusRequest ( audioFocusRequest ) ; return nextResponseValue ; }

Provides a mock like interface for the requestAudioFocus method by storing the request object
for later inspection and returning the value specified in setNextFocusRequestResponse.

Provides a mock like interface for the requestAudioFocus method by storing the request object for later inspection and returning the value specified in setNextFocusRequestResponse .


@Implementation(minSdk = O)
  protected int abandonAudioFocusRequest(android.media.AudioFocusRequest audioFocusRequest) {
    lastAbandonedAudioFocusRequest = audioFocusRequest;
    return nextResponseValue;
  }

@ Implementation ( minSdk = O ) protected int abandonAudioFocusRequest ( android . media . AudioFocusRequest audioFocusRequest ) { lastAbandonedAudioFocusRequest = audioFocusRequest ; return nextResponseValue ; }

Provides a mock like interface for the abandonAudioFocusRequest method by storing the request
object for later inspection and returning the value specified in setNextFocusRequestResponse.

Provides a mock like interface for the abandonAudioFocusRequest method by storing the request object for later inspection and returning the value specified in setNextFocusRequestResponse .


@Implementation(minSdk = LOLLIPOP)
  protected void native_start() {
    // Currently only support async-mode.
    if (callback == null) {
      return;
    }

    // Report the format as changed, to simulate adding codec specific info before making input
    // buffers available.
    HashMap<String, Object> format = new HashMap<>();
    format.put("csd-0", ByteBuffer.wrap(new byte[]{0x13, 0x10}));
    format.put("csd-1", ByteBuffer.wrap(new byte[0]));
    postFakeNativeEvent(EVENT_CALLBACK, CB_OUTPUT_FORMAT_CHANGE, 0, format);

    // Reset state.
    reachedEos = false;

    makeInputBufferAvailable(0);
  }

Starts the async encoding process, by first reporting a format change event, and then
presenting an input buffer to the callback.

Starts the async encoding process by first reporting a format change event and then presenting an input buffer to the callback .


@Implementation(minSdk = LOLLIPOP)
  protected ByteBuffer getBuffer(boolean input, int index) {
    ByteBuffer[] buffers = input ? inputBuffers : outputBuffers;

    return (index >= 0 && index < buffers.length) ? buffers[index] : null;
  }

@ Implementation ( minSdk = LOLLIPOP ) protected ByteBuffer getBuffer ( boolean input , int index ) { ByteBuffer [ ] buffers = input ? inputBuffers : outputBuffers ; return ( index >= 0 && index < buffers . length ) ? buffers [ index ] : null ; }

Returns the input or output buffer corresponding to the given index, or null if invalid.

Returns the input or output buffer corresponding to the given index or null if invalid .


@Implementation(minSdk = LOLLIPOP)
  protected void native_queueInputBuffer(
      int index, int offset, int size, long presentationTimeUs, int flags) {
    // Check if this should be the last buffer cycle.
    if ((flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
      reachedEos = true;
    }

    BufferInfo info = new BufferInfo();
    info.set(offset, size, presentationTimeUs, flags);

    makeOutputBufferAvailable(index, info);
  }

Triggers presentation of the corresponding output buffer for the given input buffer, and passes
the given metadata as buffer info.

Triggers presentation of the corresponding output buffer for the given input buffer and passes the given metadata as buffer info .


@Implementation(minSdk = LOLLIPOP)
  protected void releaseOutputBuffer(int index, boolean render, boolean updatePTS, long timeNs) {
    if (reachedEos) {
      return;
    }

    makeInputBufferAvailable(index);
  }

@ Implementation ( minSdk = LOLLIPOP ) protected void releaseOutputBuffer ( int index , boolean render , boolean updatePTS , long timeNs ) { if ( reachedEos ) { return ; } makeInputBufferAvailable ( index ) ; }

Triggers presentation of the corresponding input buffer for the given output buffer, if end of
stream has not yet been signaled.

Triggers presentation of the corresponding input buffer for the given output buffer if end of stream has not yet been signaled .