private void addMissingStyleableAttributes(PackageResourceTable resourceTable, Class<?> rClass) {
    for (Class innerClass : rClass.getClasses()) {
      if (innerClass.getSimpleName().equals("styleable")) {
        String styleableName = null; // Current styleable name
        int[] styleableArray = null; // Current styleable value array or references
        for (Field field : innerClass.getDeclaredFields()) {
          if (field.getType().equals(int[].class) && Modifier.isStatic(field.getModifiers())) {
            styleableName = field.getName();
            try {
              styleableArray = (int[]) (field.get(null));
            } catch (IllegalAccessException e) {
              throw new RuntimeException(e);
            }
          } else if (field.getType().equals(Integer.TYPE) && Modifier.isStatic(field.getModifiers())) {
            String attributeName = field.getName().substring(styleableName.length() + 1);
            try {
              int styleableIndex = field.getInt(null);
              int attributeResId = styleableArray[styleableIndex];
              resourceTable.addResource(attributeResId, "attr", attributeName);
            } catch (IllegalAccessException e) {
              throw new RuntimeException(e);
            }
          }
        }
      }
    }
  }

Check the stylable elements. Not for aapt generated R files but for framework R files it is possible to
have attributes in the styleable array for which there is no corresponding R.attr field.

Check the stylable elements . Not for aapt generated R files but for framework R files it is possible to have attributes in the styleable array for which there is no corresponding R . attr field .


public static void setWifiOn(boolean isOn) {
    Settings.Global.putInt(
        RuntimeEnvironment.application.getContentResolver(), Settings.Global.WIFI_ON, isOn ? 1 : 0);
    Settings.System.putInt(
        RuntimeEnvironment.application.getContentResolver(), Settings.System.WIFI_ON, isOn ? 1 : 0);
  }

public static void setWifiOn ( boolean isOn ) { Settings . Global . putInt ( RuntimeEnvironment . application . getContentResolver ( ) , Settings . Global . WIFI_ON , isOn ? 1 : 0 ) ; Settings . System . putInt ( RuntimeEnvironment . application . getContentResolver ( ) , Settings . System . WIFI_ON , isOn ? 1 : 0 ) ; }

Non-Android accessor that allows the value of the WIFI_ON setting to be set.

@param isOn new status for wifi mode

Non - Android accessor that allows the value of the WIFI_ON setting to be set .


@Deprecated
  public static String addSmallestScreenWidth(String qualifiers, int smallestScreenWidth) {
    int qualifiersSmallestScreenWidth = Qualifiers.getSmallestScreenWidth(qualifiers);
    if (qualifiersSmallestScreenWidth == -1) {
      if (qualifiers.length() > 0) {
        qualifiers += "-";
      }
      qualifiers += "sw" + smallestScreenWidth + "dp";
    }
    return qualifiers;
  }

@ Deprecated public static String addSmallestScreenWidth ( String qualifiers , int smallestScreenWidth ) { int qualifiersSmallestScreenWidth = Qualifiers . getSmallestScreenWidth ( qualifiers ) ; if ( qualifiersSmallestScreenWidth == - 1 ) { if ( qualifiers . length ( ) > 0 ) { qualifiers += "-" ; } qualifiers += "sw" + smallestScreenWidth + "dp" ; } return qualifiers ; }

If the Config already has a `sw` qualifier, do nothing. Otherwise, add a `sw`
qualifier for the given width.

@deprecated Use {@link android.content.res.Configuration#smallestScreenWidthDp} instead.

If the Config already has a sw qualifier do nothing . Otherwise add a sw qualifier for the given width .


protected void instrumentNativeMethod(MutableClass mutableClass, MethodNode method) {
    method.access = method.access & ~Opcodes.ACC_NATIVE;

    RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(method);
    Type returnType = generator.getReturnType();
    generator.pushDefaultReturnValueToStack(returnType);
    generator.returnValue();
  }

protected void instrumentNativeMethod ( MutableClass mutableClass , MethodNode method ) { method . access = method . access & ~ Opcodes . ACC_NATIVE ; RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter ( method ) ; Type returnType = generator . getReturnType ( ) ; generator . pushDefaultReturnValueToStack ( returnType ) ; generator . returnValue ( ) ; }

Creates native stub which returns the default return value.

@param mutableClass Class to be instrumented
@param method Method to be instrumented, must be native

Creates native stub which returns the default return value .


private void rewriteMethodBody(MutableClass mutableClass, MethodNode callingMethod) {
    ListIterator<AbstractInsnNode> instructions = callingMethod.instructions.iterator();
    while (instructions.hasNext()) {
      AbstractInsnNode node = instructions.next();

      switch (node.getOpcode()) {
        case Opcodes.NEW:
          TypeInsnNode newInsnNode = (TypeInsnNode) node;
          newInsnNode.desc = mutableClass.config.mappedTypeName(newInsnNode.desc);
          break;

        case Opcodes.GETFIELD:
          /* falls through */
        case Opcodes.PUTFIELD:
          /* falls through */
        case Opcodes.GETSTATIC:
          /* falls through */
        case Opcodes.PUTSTATIC:
          FieldInsnNode fieldInsnNode = (FieldInsnNode) node;
          fieldInsnNode.desc = mutableClass.config.mappedTypeName(fieldInsnNode.desc); // todo test
          break;

        case Opcodes.INVOKESTATIC:
          /* falls through */
        case Opcodes.INVOKEINTERFACE:
          /* falls through */
        case Opcodes.INVOKESPECIAL:
          /* falls through */
        case Opcodes.INVOKEVIRTUAL:
          MethodInsnNode targetMethod = (MethodInsnNode) node;
          targetMethod.desc = mutableClass.config.remapParams(targetMethod.desc);
          if (isGregorianCalendarBooleanConstructor(targetMethod)) {
            replaceGregorianCalendarBooleanConstructor(instructions, targetMethod);
          } else if (mutableClass.config.shouldIntercept(targetMethod)) {
            interceptInvokeVirtualMethod(mutableClass, instructions, targetMethod);
          }
          break;

        case Opcodes.INVOKEDYNAMIC:
          /* no unusual behavior */
          break;

        default:
          break;
      }
    }
  }

Filters methods that might need special treatment because of various reasons


private boolean isGregorianCalendarBooleanConstructor(MethodInsnNode targetMethod) {
    return targetMethod.owner.equals("java/util/GregorianCalendar") &&
        targetMethod.name.equals("<init>") &&
        targetMethod.desc.equals("(Z)V");
  }

private boolean isGregorianCalendarBooleanConstructor ( MethodInsnNode targetMethod ) { return targetMethod . owner . equals ( "java/util/GregorianCalendar" ) && targetMethod . name . equals ( "<init>" ) && targetMethod . desc . equals ( "(Z)V" ) ; }

Verifies if the @targetMethod is a `<init>(boolean)` constructor for
{@link java.util.GregorianCalendar}.


private void makeClassPublic(ClassNode clazz) {
    clazz.access = (clazz.access | Opcodes.ACC_PUBLIC) & ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
  }

private void makeClassPublic ( ClassNode clazz ) { clazz . access = ( clazz . access | Opcodes . ACC_PUBLIC ) & ~ ( Opcodes . ACC_PROTECTED | Opcodes . ACC_PRIVATE ) ; }

Replaces protected and private class modifiers with public.

Replaces protected and private class modifiers with public .


protected void makeMethodPublic(MethodNode method) {
    method.access = (method.access | Opcodes.ACC_PUBLIC) & ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
  }

protected void makeMethodPublic ( MethodNode method ) { method . access = ( method . access | Opcodes . ACC_PUBLIC ) & ~ ( Opcodes . ACC_PROTECTED | Opcodes . ACC_PRIVATE ) ; }

Replaces protected and private method modifiers with public.

Replaces protected and private method modifiers with public .


protected void makeMethodPrivate(MethodNode method) {
    method.access = (method.access | Opcodes.ACC_PRIVATE) & ~(Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED);
  }

protected void makeMethodPrivate ( MethodNode method ) { method . access = ( method . access | Opcodes . ACC_PRIVATE ) & ~ ( Opcodes . ACC_PUBLIC | Opcodes . ACC_PROTECTED ) ; }

Replaces protected and public class modifiers with private.

Replaces protected and public class modifiers with private .


public void setTraversalAfter(AccessibilityNodeInfo info) {
    if (this.traversalAfter != null) {
      this.traversalAfter.recycle();
    }

    this.traversalAfter = obtain(info);
  }

public void setTraversalAfter ( AccessibilityNodeInfo info ) { if ( this . traversalAfter != null ) { this . traversalAfter . recycle ( ) ; } this . traversalAfter = obtain ( info ) ; }

Sets the view whose node is visited after this one in accessibility traversal.

This may be useful for configuring traversal order in tests before the corresponding
views have been inflated.

@param info The previous node.
@see #getTraversalAfter()

Sets the view whose node is visited after this one in accessibility traversal .


public void setTraversalBefore(AccessibilityNodeInfo info) {
    if (this.traversalBefore != null) {
      this.traversalBefore.recycle();
    }

    this.traversalBefore = obtain(info);
  }

public void setTraversalBefore ( AccessibilityNodeInfo info ) { if ( this . traversalBefore != null ) { this . traversalBefore . recycle ( ) ; } this . traversalBefore = obtain ( info ) ; }

Sets the view before whose node this one should be visited during traversal.

This may be useful for configuring traversal order in tests before the corresponding
views have been inflated.

@param info The view providing the preceding node.
@see #getTraversalBefore()

Sets the view before whose node this one should be visited during traversal .


public void addChild(AccessibilityNodeInfo child) {
    if (children == null) {
      children = new ArrayList<>();
    }

    children.add(child);
    ShadowAccessibilityNodeInfo shadowAccessibilityNodeInfo = Shadow.extract(child);
    shadowAccessibilityNodeInfo.parent = realAccessibilityNodeInfo;
  }

public void addChild ( AccessibilityNodeInfo child ) { if ( children == null ) { children = new ArrayList <> ( ) ; } children . add ( child ) ; ShadowAccessibilityNodeInfo shadowAccessibilityNodeInfo = Shadow . extract ( child ) ; shadowAccessibilityNodeInfo . parent = realAccessibilityNodeInfo ; }

Add a child node to this one. Also initializes the parent field of the
child.

@param child The node to be added as a child.

Add a child node to this one . Also initializes the parent field of the child .


public void pushDefaultReturnValueToStack(Type type) {
    if (type.equals(Type.BOOLEAN_TYPE)) {
      push(false);
    } else if (type.equals(Type.INT_TYPE) || type.equals(Type.SHORT_TYPE) || type.equals(Type.BYTE_TYPE) || type.equals(Type.CHAR_TYPE)) {
      push(0);
    } else if (type.equals(Type.LONG_TYPE)) {
      push(0L);
    } else if (type.equals(Type.FLOAT_TYPE)) {
      push(0f);
    } else if (type.equals(Type.DOUBLE_TYPE)) {
      push(0d);
    } else if (type.getSort() == ARRAY || type.getSort() == OBJECT) {
      loadNull();
    }
  }

public void pushDefaultReturnValueToStack ( Type type ) { if ( type . equals ( Type . BOOLEAN_TYPE ) ) { push ( false ) ; } else if ( type . equals ( Type . INT_TYPE ) || type . equals ( Type . SHORT_TYPE ) || type . equals ( Type . BYTE_TYPE ) || type . equals ( Type . CHAR_TYPE ) ) { push ( 0 ) ; } else if ( type . equals ( Type . LONG_TYPE ) ) { push ( 0L ) ; } else if ( type . equals ( Type . FLOAT_TYPE ) ) { push ( 0f ) ; } else if ( type . equals ( Type . DOUBLE_TYPE ) ) { push ( 0d ) ; } else if ( type . getSort ( ) == ARRAY || type . getSort ( ) == OBJECT ) { loadNull ( ) ; } }

Forces a return of a default value, depending on the method's return type

@param type The method's return type

Forces a return of a default value depending on the method s return type


public static int getMode(String path) {
    if (path == null) {
      return 0;
    }

    File file = new File(path);
    if (file.isDirectory()) {
      return S_IFDIR_VALUE;
    }
    if (file.isFile()) {
      return S_IFREG_VALUE;
    }
    if (!canonicalize(path).equals(path)) {
      return S_IFLNK_VALUE;
    }
    return 0;
  }

public static int getMode ( String path ) { if ( path == null ) { return 0 ; } File file = new File ( path ) ; if ( file . isDirectory ( ) ) { return S_IFDIR_VALUE ; } if ( file . isFile ( ) ) { return S_IFREG_VALUE ; } if ( ! canonicalize ( path ) . equals ( path ) ) { return S_IFLNK_VALUE ; } return 0 ; }


public ActivityController<T> setup(Bundle savedInstanceState) {
    return create(savedInstanceState)
        .start()
        .restoreInstanceState(savedInstanceState)
        .postCreate(savedInstanceState)
        .resume()
        .visible();
  }

public ActivityController < T > setup ( Bundle savedInstanceState ) { return create ( savedInstanceState ) . start ( ) . restoreInstanceState ( savedInstanceState ) . postCreate ( savedInstanceState ) . resume ( ) . visible ( ) ; }

Calls the same lifecycle methods on the Activity called by Android when an Activity is restored from previously saved state.

@param savedInstanceState Saved instance state.
@return Activity controller instance.

Calls the same lifecycle methods on the Activity called by Android when an Activity is restored from previously saved state .


public ActivityController<T> configurationChange(final Configuration newConfiguration) {
    final Configuration currentConfig = component.getResources().getConfiguration();
    final int changedBits = currentConfig.diff(newConfiguration);
    currentConfig.setTo(newConfiguration);

    // TODO: throw on changedBits == 0 since it non-intuitively calls onConfigurationChanged

    // Can the activity handle itself ALL configuration changes?
    if ((getActivityInfo(component.getApplication()).configChanges & changedBits) == changedBits) {
      shadowMainLooper.runPaused(() -> component.onConfigurationChanged(newConfiguration));

      return this;
    } else {
      @SuppressWarnings("unchecked")
      final T recreatedActivity = (T) ReflectionHelpers.callConstructor(component.getClass());
      final _Activity_ _recreatedActivity_ = reflector(_Activity_.class, recreatedActivity);

      shadowMainLooper.runPaused(
          new Runnable() {
            @Override
            public void run() {
              // Set flags
              ReflectionHelpers.setField(
                  Activity.class, component, "mChangingConfigurations", true);
              ReflectionHelpers.setField(
                  Activity.class, component, "mConfigChangeFlags", changedBits);

              // Perform activity destruction
              final Bundle outState = new Bundle();

              // The order of onPause/onStop/onSaveInstanceState is undefined, but is usually:
              // onPause -> onSaveInstanceState -> onStop
              _component_.performPause();
              _component_.performSaveInstanceState(outState);
              if (RuntimeEnvironment.getApiLevel() <= M) {
                _component_.performStop();
              } else if (RuntimeEnvironment.getApiLevel() <= O_MR1) {
                _component_.performStop(true);
              } else {
                _component_.performStop(true, "configurationChange");
              }

              // This is the true and complete retained state, including loaders and retained
              // fragments.
              final Object nonConfigInstance = _component_.retainNonConfigurationInstances();
              // This is the activity's "user" state
              final Object activityConfigInstance =
                  nonConfigInstance == null
                      ? null // No framework or user state.
                      : reflector(_NonConfigurationInstances_.class, nonConfigInstance)
                          .getActivity();

              _component_.performDestroy();

              // Restore theme in case it was set in the test manually.
              // This is not technically what happens but is purely to make this easier to use in
              // Robolectric.
              ShadowContextThemeWrapper shadowContextThemeWrapper = Shadow.extract(component);
              int theme = shadowContextThemeWrapper.callGetThemeResId();

              // Setup controller for the new activity
              attached = false;
              component = recreatedActivity;
              _component_ = _recreatedActivity_;

              // TODO: Pass nonConfigurationInstance here instead of setting
              // mLastNonConfigurationInstances directly below. This field must be set before
              // attach. Since current implementation sets it after attach(), initialization is not
              // done correctly. For instance, fragment marked as retained is not retained.
              attach(/*lastNonConfigurationInstances=*/ null);

              if (theme != 0) {
                recreatedActivity.setTheme(theme);
              }

              // Set saved non config instance
              _recreatedActivity_.setLastNonConfigurationInstances(nonConfigInstance);
              ShadowActivity shadowActivity = Shadow.extract(recreatedActivity);
              shadowActivity.setLastNonConfigurationInstance(activityConfigInstance);

              // Create lifecycle
              _recreatedActivity_.performCreate(outState);

              if (RuntimeEnvironment.getApiLevel() <= O_MR1) {

                _recreatedActivity_.performStart();

              } else {
                _recreatedActivity_.performStart("configurationChange");
              }

              _recreatedActivity_.performRestoreInstanceState(outState);
              _recreatedActivity_.onPostCreate(outState);
              if (RuntimeEnvironment.getApiLevel() <= O_MR1) {
                _recreatedActivity_.performResume();
              } else {
                _recreatedActivity_.performResume(true, "configurationChange");
              }
              _recreatedActivity_.onPostResume();
              // TODO: Call visible() too.
            }
          });
    }

    return this;
  }

Performs a configuration change on the Activity.

If the activity is configured to handle changes without being recreated,
{@link Activity#onConfigurationChanged(Configuration)} will be called. Otherwise, the activity
is recreated as described [here](https://developer.android.com/guide/topics/resources/runtime-changes.html).

@param newConfiguration The new configuration to be set.
@return ActivityController instance

Performs a configuration change on the Activity .


@SuppressWarnings("unchecked")
  public ActivityController<T> recreate() {
    Stage originalStage =
        ActivityLifecycleMonitorRegistry.getInstance().getLifecycleStageOf(component);

    switch (originalStage) {
      case PRE_ON_CREATE:
        create();
        // fall through
      case CREATED:
      case RESTARTED:
        start();
        postCreate(null);
        // fall through
      case STARTED:
        resume();
        // fall through
      case RESUMED:
        pause();
        // fall through
      case PAUSED:
        stop();
        // fall through
      case STOPPED:
        break;
      default:
        throw new IllegalStateException("Cannot recreate activity since it's destroyed already");
    }

    // Activity#mChangingConfigurations flag should be set prior to Activity recreation process
    // starts. ActivityThread does set it on real device but here we simulate the Activity
    // recreation process on behalf of ActivityThread so set the flag here. Note we don't need to
    // reset the flag to false because this Activity instance is going to be destroyed and disposed.
    // https://android.googlesource.com/platform/frameworks/base/+/55418eada51d4f5e6532ae9517af66c50
    // ea495c4/core/java/android/app/ActivityThread.java#4806
    ReflectionHelpers.setField(component, "mChangingConfigurations", true);

    Bundle outState = new Bundle();
    saveInstanceState(outState);
    Object lastNonConfigurationInstances =
        ReflectionHelpers.callInstanceMethod(component, "retainNonConfigurationInstances");
    destroy();

    component = (T) ReflectionHelpers.callConstructor(component.getClass());
    _component_ = reflector(_Activity_.class, component);
    attached = false;
    attach(lastNonConfigurationInstances);
    create(outState);
    start();
    restoreInstanceState(outState);
    postCreate(outState);
    resume();
    postResume();
    visible();
    windowFocusChanged(true);

    // Move back to the original stage. If the original stage was transient stage, it will bring it
    // to resumed state to match the on device behavior.
    switch (originalStage) {
      case PAUSED:
        pause();
        return this;
      case STOPPED:
        pause();
        stop();
        return this;
      default:
        return this;
    }
  }

Recreates activity instance which is controlled by this ActivityController.
NonConfigurationInstances and savedInstanceStateBundle are properly passed into a new instance.
After the recreation, it brings back its lifecycle state to the original state. The activity
should not be destroyed yet.

Recreates activity instance which is controlled by this ActivityController . NonConfigurationInstances and savedInstanceStateBundle are properly passed into a new instance . After the recreation it brings back its lifecycle state to the original state . The activity should not be destroyed yet .


public void setCallState(int callState, String incomingPhoneNumber) {
    if (callState != CALL_STATE_RINGING) {
      incomingPhoneNumber = null;
    }

    this.callState = callState;
    this.incomingPhoneNumber = incomingPhoneNumber;

    for (PhoneStateListener listener : getListenersForFlags(LISTEN_CALL_STATE)) {
      listener.onCallStateChanged(callState, incomingPhoneNumber);
    }
  }

public void setCallState ( int callState , String incomingPhoneNumber ) { if ( callState != CALL_STATE_RINGING ) { incomingPhoneNumber = null ; } this . callState = callState ; this . incomingPhoneNumber = incomingPhoneNumber ; for ( PhoneStateListener listener : getListenersForFlags ( LISTEN_CALL_STATE ) ) { listener . onCallStateChanged ( callState , incomingPhoneNumber ) ; } }

Sets the current call state with the option to specify an incoming phone number for the
CALL_STATE_RINGING state. The incoming phone number will be ignored for all other cases.

Sets the current call state with the option to specify an incoming phone number for the CALL_STATE_RINGING state . The incoming phone number will be ignored for all other cases .


public void expectLogMessage(int level, String tag, String message) {
    checkTag(tag);
    expectedLogs.add(new LogItem(level, tag, message, null));
  }

public void expectLogMessage ( int level , String tag , String message ) { checkTag ( tag ) ; expectedLogs . add ( new LogItem ( level , tag , message , null ) ) ; }

Adds an expected log statement. If this log is not printed during test execution, the test case
will fail. Do not use this to suppress failures. Use this to test that expected error cases in
your code cause log messages to be printed.

Adds an expected log statement . If this log is not printed during test execution the test case will fail . Do not use this to suppress failures . Use this to test that expected error cases in your code cause log messages to be printed .


public boolean isExported() {
    boolean defaultValue = !intentFilters.isEmpty();
    return (attributes.containsKey(EXPORTED)
        ? Boolean.parseBoolean(attributes.get(EXPORTED))
        : defaultValue);
  }

public boolean isExported ( ) { boolean defaultValue = ! intentFilters . isEmpty ( ) ; return ( attributes . containsKey ( EXPORTED ) ? Boolean . parseBoolean ( attributes . get ( EXPORTED ) ) : defaultValue ) ; }

Returns whether this service is exported by checking the XML attribute.

@return true if the service is exported

Returns whether this service is exported by checking the XML attribute .


private static void getShapeEndPoint(int type, float[] coords, float[] point) {
    // start index of the end point for the segment type
    int pointIndex = (getNumberOfPoints(type) - 1) * 2;
    point[0] = coords[pointIndex];
    point[1] = coords[pointIndex + 1];
  }

Returns the end point of a given segment

@param type the segment type
@param coords the segment coordinates array
@param point the return array where the point will be stored


private void getPointAtLength(
      int type, float[] coords, float lastX, float lastY, float t, float[] point) {
    if (type == PathIterator.SEG_LINETO) {
      point[0] = lastX + (coords[0] - lastX) * t;
      point[1] = lastY + (coords[1] - lastY) * t;
      // Return here, since we do not need a shape to estimate
      return;
    }

    float[] curve = new float[8];
    int lastPointIndex = (getNumberOfPoints(type) - 1) * 2;

    System.arraycopy(coords, 0, curve, 2, coords.length);
    curve[0] = lastX;
    curve[1] = lastY;
    if (type == PathIterator.SEG_CUBICTO) {
      cubicCurveSegment(curve, 0f, t);
    } else {
      quadCurveSegment(curve, 0f, t);
    }

    point[0] = curve[2 + lastPointIndex];
    point[1] = curve[2 + lastPointIndex + 1];
  }

Returns the estimated position along a path of the given length.

Returns the estimated position along a path of the given length .


static ResTable_config createConfig(ByteBuffer buffer) {
    int startPosition = buffer.position();  // The starting buffer position to calculate bytes read.
    int size = buffer.getInt();
    int mcc = buffer.getShort() & 0xFFFF;
    int mnc = buffer.getShort() & 0xFFFF;
    byte[] language = new byte[2];
    buffer.get(language);
    byte[] region = new byte[2];
    buffer.get(region);
    int orientation = UnsignedBytes.toInt(buffer.get());
    int touchscreen = UnsignedBytes.toInt(buffer.get());
    int density = buffer.getShort() & 0xFFFF;
    int keyboard = UnsignedBytes.toInt(buffer.get());
    int navigation = UnsignedBytes.toInt(buffer.get());
    int inputFlags = UnsignedBytes.toInt(buffer.get());
    buffer.get();  // 1 byte of padding
    int screenWidth = buffer.getShort() & 0xFFFF;
    int screenHeight = buffer.getShort() & 0xFFFF;
    int sdkVersion = buffer.getShort() & 0xFFFF;
    int minorVersion = buffer.getShort() & 0xFFFF;

    // At this point, the configuration's size needs to be taken into account as not all
    // configurations have all values.
    int screenLayout = 0;
    int uiMode = 0;
    int smallestScreenWidthDp = 0;
    int screenWidthDp = 0;
    int screenHeightDp = 0;
    byte[] localeScript = new byte[4];
    byte[] localeVariant = new byte[8];
    byte screenLayout2 = 0;
    byte screenConfigPad1 = 0;
    short screenConfigPad2 = 0;

    if (size >= SCREEN_CONFIG_MIN_SIZE) {
      screenLayout = UnsignedBytes.toInt(buffer.get());
      uiMode = UnsignedBytes.toInt(buffer.get());
      smallestScreenWidthDp = buffer.getShort() & 0xFFFF;
    }

    if (size >= SCREEN_DP_MIN_SIZE) {
      screenWidthDp = buffer.getShort() & 0xFFFF;
      screenHeightDp = buffer.getShort() & 0xFFFF;
    }

    if (size >= LOCALE_MIN_SIZE) {
      buffer.get(localeScript);
      buffer.get(localeVariant);
    }

    if (size >= SCREEN_CONFIG_EXTENSION_MIN_SIZE) {
      screenLayout2 = (byte) UnsignedBytes.toInt(buffer.get());
      screenConfigPad1 = buffer.get();  // Reserved padding
      screenConfigPad2 = buffer.getShort();  // More reserved padding
    }

    // After parsing everything that's known, account for anything that's unknown.
    int bytesRead = buffer.position() - startPosition;
    byte[] unknown = new byte[size - bytesRead];
    buffer.get(unknown);

    return new ResTable_config(size, mcc, mnc, language, region, orientation,
        touchscreen, density, keyboard, navigation, inputFlags, screenWidth, screenHeight,
        sdkVersion, minorVersion, screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp,
        screenHeightDp, localeScript, localeVariant, screenLayout2, screenConfigPad1, screenConfigPad2, unknown);
  }


int diff(final ResTable_config o) {
    int diffs = 0;
    if (mcc != o.mcc) diffs |= CONFIG_MCC;
    if (mnc != o.mnc) diffs |= CONFIG_MNC;
    if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
    if (density != o.density) diffs |= CONFIG_DENSITY;
    if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
    if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
      diffs |= CONFIG_KEYBOARD_HIDDEN;
    if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
    if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
    if (screenSize() != o.screenSize()) diffs |= CONFIG_SCREEN_SIZE;
    if (version() != o.version()) diffs |= CONFIG_VERSION;
    if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR;
    if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT;
    if ((screenLayout2 & MASK_SCREENROUND) != (o.screenLayout2 & MASK_SCREENROUND)) diffs |= CONFIG_SCREEN_ROUND;
    if ((colorMode & MASK_WIDE_COLOR_GAMUT) != (o.colorMode & MASK_WIDE_COLOR_GAMUT)) diffs |= CONFIG_COLOR_MODE;
    if ((colorMode & MASK_HDR) != (o.colorMode & MASK_HDR)) diffs |= CONFIG_COLOR_MODE;
    if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
    if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
    if (screenSizeDp() != o.screenSizeDp()) diffs |= CONFIG_SCREEN_SIZE;

    int diff = compareLocales(this, o);
    if (isTruthy(diff)) diffs |= CONFIG_LOCALE;

    return diffs;
  }

int diff ( final ResTable_config o ) { int diffs = 0 ; if ( mcc != o . mcc ) diffs |= CONFIG_MCC ; if ( mnc != o . mnc ) diffs |= CONFIG_MNC ; if ( orientation != o . orientation ) diffs |= CONFIG_ORIENTATION ; if ( density != o . density ) diffs |= CONFIG_DENSITY ; if ( touchscreen != o . touchscreen ) diffs |= CONFIG_TOUCHSCREEN ; if ( ( ( inputFlags ^ o . inputFlags ) & ( MASK_KEYSHIDDEN | MASK_NAVHIDDEN ) ) != 0 ) diffs |= CONFIG_KEYBOARD_HIDDEN ; if ( keyboard != o . keyboard ) diffs |= CONFIG_KEYBOARD ; if ( navigation != o . navigation ) diffs |= CONFIG_NAVIGATION ; if ( screenSize ( ) != o . screenSize ( ) ) diffs |= CONFIG_SCREEN_SIZE ; if ( version ( ) != o . version ( ) ) diffs |= CONFIG_VERSION ; if ( ( screenLayout & MASK_LAYOUTDIR ) != ( o . screenLayout & MASK_LAYOUTDIR ) ) diffs |= CONFIG_LAYOUTDIR ; if ( ( screenLayout & ~ MASK_LAYOUTDIR ) != ( o . screenLayout & ~ MASK_LAYOUTDIR ) ) diffs |= CONFIG_SCREEN_LAYOUT ; if ( ( screenLayout2 & MASK_SCREENROUND ) != ( o . screenLayout2 & MASK_SCREENROUND ) ) diffs |= CONFIG_SCREEN_ROUND ; if ( ( colorMode & MASK_WIDE_COLOR_GAMUT ) != ( o . colorMode & MASK_WIDE_COLOR_GAMUT ) ) diffs |= CONFIG_COLOR_MODE ; if ( ( colorMode & MASK_HDR ) != ( o . colorMode & MASK_HDR ) ) diffs |= CONFIG_COLOR_MODE ; if ( uiMode != o . uiMode ) diffs |= CONFIG_UI_MODE ; if ( smallestScreenWidthDp != o . smallestScreenWidthDp ) diffs |= CONFIG_SMALLEST_SCREEN_SIZE ; if ( screenSizeDp ( ) != o . screenSizeDp ( ) ) diffs |= CONFIG_SCREEN_SIZE ; int diff = compareLocales ( this , o ) ; if ( isTruthy ( diff ) ) diffs |= CONFIG_LOCALE ; return diffs ; }


public final boolean isDefault() {
    return mcc == 0
        && mnc == 0
        && isZeroes(language)
        && isZeroes(country)
        && orientation == 0
        && touchscreen == 0
        && density == 0
        && keyboard == 0
        && navigation == 0
        && inputFlags == 0
        && screenWidth == 0
        && screenHeight == 0
        && sdkVersion == 0
        && minorVersion == 0
        && screenLayout == 0
        && uiMode == 0
        && smallestScreenWidthDp == 0
        && screenWidthDp == 0
        && screenHeightDp == 0
        && isZeroes(localeScript)
        && isZeroes(localeVariant)
        && screenLayout2 == 0
        && colorMode == 0
        ;
  }

public final boolean isDefault ( ) { return mcc == 0 && mnc == 0 && isZeroes ( language ) && isZeroes ( country ) && orientation == 0 && touchscreen == 0 && density == 0 && keyboard == 0 && navigation == 0 && inputFlags == 0 && screenWidth == 0 && screenHeight == 0 && sdkVersion == 0 && minorVersion == 0 && screenLayout == 0 && uiMode == 0 && smallestScreenWidthDp == 0 && screenWidthDp == 0 && screenHeightDp == 0 && isZeroes ( localeScript ) && isZeroes ( localeVariant ) && screenLayout2 == 0 && colorMode == 0 ; }

Returns true if this is the default "any" configuration.

Returns true if this is the default any configuration .


@Implementation(minSdk = JELLY_BEAN_MR2)
  protected Bundle getApplicationRestrictions(String packageName) {
    Bundle bundle = applicationRestrictions.get(packageName);
    return bundle != null ? bundle : new Bundle();
  }

@ Implementation ( minSdk = JELLY_BEAN_MR2 ) protected Bundle getApplicationRestrictions ( String packageName ) { Bundle bundle = applicationRestrictions . get ( packageName ) ; return bundle != null ? bundle : new Bundle ( ) ; }

Compared to real Android, there is no check that the package name matches the application
package name and the method returns instantly.

@see #setApplicationRestrictions(String, Bundle)

Compared to real Android there is no check that the package name matches the application package name and the method returns instantly .


public long addUserProfile(UserHandle userHandle) {
    long serialNumber = nextUserSerial++;
    userProfiles.put(userHandle, serialNumber);
    return serialNumber;
  }

public long addUserProfile ( UserHandle userHandle ) { long serialNumber = nextUserSerial ++ ; userProfiles . put ( userHandle , serialNumber ) ; return serialNumber ; }

Adds a profile associated for the user that the calling process is running on.

The user is assigned an arbitrary unique serial number.

@return the user's serial number

Adds a profile associated for the user that the calling process is running on .


public UserHandle addUser(int id, String name, int flags) {
    UserHandle userHandle =
        id == UserHandle.USER_SYSTEM ? Process.myUserHandle() : new UserHandle(id);
    addUserProfile(userHandle);
    setSerialNumberForUser(userHandle, (long) id);
    userInfoMap.put(id, new UserInfo(id, name, flags));
    userPidMap.put(
        id,
        id == UserHandle.USER_SYSTEM
            ? Process.myUid()
            : id * UserHandle.PER_USER_RANGE + ShadowProcess.getRandomApplicationUid());
    return userHandle;
  }

public UserHandle addUser ( int id , String name , int flags ) { UserHandle userHandle = id == UserHandle . USER_SYSTEM ? Process . myUserHandle ( ) : new UserHandle ( id ) ; addUserProfile ( userHandle ) ; setSerialNumberForUser ( userHandle , ( long ) id ) ; userInfoMap . put ( id , new UserInfo ( id , name , flags ) ) ; userPidMap . put ( id , id == UserHandle . USER_SYSTEM ? Process . myUid ( ) : id * UserHandle . PER_USER_RANGE + ShadowProcess . getRandomApplicationUid ( ) ) ; return userHandle ; }

Creates a user with the specified name, userId and flags.

@param id the unique id of user
@param name name of the user
@param flags 16 bits for user type. See {@link UserInfo#flags}
@return a handle to the new user

Creates a user with the specified name userId and flags .


@Implementation
  protected void connect() throws IOException {
    if (state == SocketState.CLOSED) {
      throw new IOException("socket closed");
    }
    state = SocketState.CONNECTED;
  }

@
Implementation
protected
void
connect
(
)
throws
IOException
{
if
(
state
==
SocketState
.
CLOSED
)
{
throw
new
IOException
(
"socket closed"
)
;
}
state
=
SocketState
.
CONNECTED
;
}

This method doesn't perform an actual connection and returns immediately

This method doesn t perform an actual connection and returns immediately


private void interceptInvokeVirtualMethodWithInvokeDynamic(
      ListIterator<AbstractInsnNode> instructions, MethodInsnNode targetMethod) {
    instructions.remove();  // remove the method invocation

    Type type = Type.getObjectType(targetMethod.owner);
    String description = targetMethod.desc;
    String owner = type.getClassName();

    if (targetMethod.getOpcode() != Opcodes.INVOKESTATIC) {
      String thisType = type.getDescriptor();
      description = "(" + thisType + description.substring(1);
    }

    instructions.add(new InvokeDynamicInsnNode(targetMethod.name, description, BOOTSTRAP_INTRINSIC, owner));
  }

Intercepts the method using the invokedynamic bytecode instruction available in Java 7+.
Should be called through interceptInvokeVirtualMethod, not directly.

Intercepts the method using the invokedynamic bytecode instruction available in Java 7 + . Should be called through interceptInvokeVirtualMethod not directly .


int addMappings(final DynamicRefTable other) {
    if (mAssignedPackageId != other.mAssignedPackageId) {
      return UNKNOWN_ERROR;
    }

//    final int entryCount = other.mEntries.size();
//    for (size_t i = 0; i < entryCount; i++) {
//      ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i));
//      if (index < 0) {
//        mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]);
//      } else {
//        if (other.mEntries[i] != mEntries[index]) {
//          return UNKNOWN_ERROR;
//        }
//      }
//    }
    for (Entry<String, Byte> otherEntry : other.mEntries.entrySet()) {
      String key = otherEntry.getKey();
      Byte curValue = mEntries.get(key);
      if (curValue == null) {
        mEntries.put(key, otherEntry.getValue());
      } else {
        if (!Objects.equals(otherEntry.getValue(), curValue)) {
          return UNKNOWN_ERROR;
        }
      }
    }

    // Merge the lookup table. No entry can conflict
    // (value of 0 means not set).
    for (int i = 0; i < 256; i++) {
      if (mLookupTable[i] != other.mLookupTable[i]) {
        if (mLookupTable[i] == 0) {
          mLookupTable[i] = other.mLookupTable[i];
        } else if (other.mLookupTable[i] != 0) {
          return UNKNOWN_ERROR;
        }
      }
    }
    return NO_ERROR;
  }

Adds mappings from the other DynamicRefTable


int addMapping(final String packageName, byte packageId) {
    Byte index = mEntries.get(packageName);
    if (index == null) {
      return UNKNOWN_ERROR;
    }
    mLookupTable[index] = packageId;
    return NO_ERROR;
  }

int addMapping ( final String packageName , byte packageId ) { Byte index = mEntries . get ( packageName ) ; if ( index == null ) { return UNKNOWN_ERROR ; } mLookupTable [ index ] = packageId ; return NO_ERROR ; }


public void grantPermissions(int pid, int uid, String... permissions) {
    getShadowInstrumentation().grantPermissions(pid, uid, permissions);
  }

public void grantPermissions ( int pid , int uid , String ... permissions ) { getShadowInstrumentation ( ) . grantPermissions ( pid , uid , permissions ) ; }

Grant the given permissions for the given process and user.

Grant the given permissions for the given process and user .


public void denyPermissions(int pid, int uid, String... permissions) {
    getShadowInstrumentation().denyPermissions(pid, uid, permissions);
  }

public void denyPermissions ( int pid , int uid , String ... permissions ) { getShadowInstrumentation ( ) . denyPermissions ( pid , uid , permissions ) ; }

Revoke the given permissions for the given process and user.

Revoke the given permissions for the given process and user .


@Override
  @Nonnull
  public List<Sdk> selectSdks(Configuration configuration, UsesSdk usesSdk) {
    Config config = configuration.get(Config.class);
    Set<Sdk> sdks = new TreeSet<>(configuredSdks(config, usesSdk));
    if (enabledSdks != null) {
      sdks = Sets.intersection(sdks, enabledSdks);
    }
    return Lists.newArrayList(sdks);
  }

@ Override @ Nonnull public List < Sdk > selectSdks ( Configuration configuration , UsesSdk usesSdk ) { Config config = configuration . get ( Config . class ) ; Set < Sdk > sdks = new TreeSet <> ( configuredSdks ( config , usesSdk ) ) ; if ( enabledSdks != null ) { sdks = Sets . intersection ( sdks , enabledSdks ) ; } return Lists . newArrayList ( sdks ) ; }

Enumerate the SDKs to be used for this test.

@param configuration a collection of configuration objects, including {@link Config}
@param usesSdk the {@link UsesSdk} for the test
@return the list of candidate {@link Sdk}s.
@since 3.9

Enumerate the SDKs to be used for this test .


private static Path getFileFromZip(Path path) {
    byte[] buffer = new byte[1024];
    try {
      Path outputDir = new TempDirectory("robolectric_assets").create("fromzip");
      try (InputStream zis = Fs.getInputStream(path)) {
        Path fileFromZip = outputDir.resolve(path.getFileName().toString());

        try (OutputStream fos = Files.newOutputStream(fileFromZip)) {
          int len;
          while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
          }
        }
        return fileFromZip;
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

private static Path getFileFromZip ( Path path ) { byte [ ] buffer = new byte [ 1024 ] ; try { Path outputDir = new TempDirectory ( "robolectric_assets" ) . create ( "fromzip" ) ; try ( InputStream zis = Fs . getInputStream ( path ) ) { Path fileFromZip = outputDir . resolve ( path . getFileName ( ) . toString ( ) ) ; try ( OutputStream fos = Files . newOutputStream ( fileFromZip ) ) { int len ; while ( ( len = zis . read ( buffer ) ) > 0 ) { fos . write ( buffer , 0 , len ) ; } } return fileFromZip ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }

Extract an asset from a zipped up assets provided by the build system, this is required because
there is no way to get a FileDescriptor from a zip entry. This is a temporary measure for Bazel
which can be removed once binary resources are supported.

Extract an asset from a zipped up assets provided by the build system this is required because there is no way to get a FileDescriptor from a zip entry . This is a temporary measure for Bazel which can be removed once binary resources are supported .


public static HttpRequest getNextSentHttpRequest() {
    HttpRequestInfo httpRequestInfo = getFakeHttpLayer().getNextSentHttpRequestInfo();
    return httpRequestInfo == null ? null : httpRequestInfo.getHttpRequest();
  }

public static HttpRequest getNextSentHttpRequest ( ) { HttpRequestInfo httpRequestInfo = getFakeHttpLayer ( ) . getNextSentHttpRequestInfo ( ) ; return httpRequestInfo == null ? null : httpRequestInfo . getHttpRequest ( ) ; }

Accessor to obtain HTTP requests made during the current test in the order in which they were made.

@return the requested request or null if there are none.

Accessor to obtain HTTP requests made during the current test in the order in which they were made .


public static void addHttpResponseRule(String method, String uri, HttpResponse response) {
    getFakeHttpLayer().addHttpResponseRule(method, uri, response);
  }

public static void addHttpResponseRule ( String method , String uri , HttpResponse response ) { getFakeHttpLayer ( ) . addHttpResponseRule ( method , uri , response ) ; }

Adds an HTTP response rule. The response will be returned when the rule is matched.

@param method   method to match.
@param uri      uri to match.
@param response response to return when a match is found.

Adds an HTTP response rule . The response will be returned when the rule is matched .


public static void addHttpResponseRule(RequestMatcher requestMatcher, List<? extends HttpResponse> responses) {
    getFakeHttpLayer().addHttpResponseRule(requestMatcher, responses);
  }

public static void addHttpResponseRule ( RequestMatcher requestMatcher , List < ? extends HttpResponse > responses ) { getFakeHttpLayer ( ) . addHttpResponseRule ( requestMatcher , responses ) ; }

Adds an HTTP response rule. For each time the rule is matched, responses will be shifted
off the list and returned. When all responses have been given and the rule is matched again,
an exception will be thrown.

@param requestMatcher custom {@code RequestMatcher}.
@param responses      responses to return in order when a match is found.

Adds an HTTP response rule . For each time the rule is matched responses will be shifted off the list and returned . When all responses have been given and the rule is matched again an exception will be thrown .


@Implementation
  protected static void nativeStop(long nativeObject) {
    try {
      // Close the output stream.
      getStream(nativeObject).close();

      // Clear the stream from both internal caches.
      fdToStream.remove(outputStreams.remove(nativeObject).getFD());
    } catch (IOException e) {
      throw new RuntimeException("Unable to close temporary file.", e);
    }
  }

Closes the FileOutputStream for the associated muxer.

Closes the FileOutputStream for the associated muxer .


public void addHttpResponseRule(RequestMatcher requestMatcher, List<? extends HttpResponse> responses) {
    addHttpResponseRule(new RequestMatcherResponseRule(requestMatcher, responses));
  }

public void addHttpResponseRule ( RequestMatcher requestMatcher , List < ? extends HttpResponse > responses ) { addHttpResponseRule ( new RequestMatcherResponseRule ( requestMatcher , responses ) ) ; }

Add a response rule.

@param requestMatcher Request matcher
@param responses      A list of responses that are returned to matching requests in order from first to last.


public void addBluetoothRoute() {
    updateBluetoothAudioRoute(BLUETOOTH_DEVICE_NAME);

    if (RuntimeEnvironment.getApiLevel() <= JELLY_BEAN_MR1) {
      ReflectionHelpers.callInstanceMethod(
          MediaRouter.class,
          realObject,
          "selectRouteInt",
          ClassParameter.from(int.class, MediaRouter.ROUTE_TYPE_LIVE_AUDIO),
          ClassParameter.from(RouteInfo.class, getBluetoothA2dpRoute()));
    } else {
      realObject.selectRoute(MediaRouter.ROUTE_TYPE_LIVE_AUDIO, getBluetoothA2dpRoute());
    }
  }

public void addBluetoothRoute ( ) { updateBluetoothAudioRoute ( BLUETOOTH_DEVICE_NAME ) ; if ( RuntimeEnvironment . getApiLevel ( ) <= JELLY_BEAN_MR1 ) { ReflectionHelpers . callInstanceMethod ( MediaRouter . class , realObject , "selectRouteInt" , ClassParameter . from ( int . class , MediaRouter . ROUTE_TYPE_LIVE_AUDIO ) , ClassParameter . from ( RouteInfo . class , getBluetoothA2dpRoute ( ) ) ) ; } else { realObject . selectRoute ( MediaRouter . ROUTE_TYPE_LIVE_AUDIO , getBluetoothA2dpRoute ( ) ) ; } }

Adds the Bluetooth A2DP route and ensures it's the selected route, simulating connecting a
Bluetooth device.

Adds the Bluetooth A2DP route and ensures it s the selected route simulating connecting a Bluetooth device .


@Implementation
  protected static final void setThreadPriority(int tid, int priority) {
    checkArgument(
        priority >= android.os.Process.THREAD_PRIORITY_URGENT_AUDIO
            && priority <= android.os.Process.THREAD_PRIORITY_LOWEST,
        "priority %s out of range. Use a Process.THREAD_PRIORITY_* constant.",
        priority);

    if (tid == 0) {
      tid = ShadowProcess.myTid();
    }
    synchronized (threadPrioritiesLock) {
      threadPriorities.put(tid, priority);
    }
  }

Stores priority for the given thread, but doesn't actually change it to not mess up with test
runner. Unlike real implementation does not throw any exceptions.

@param tid The identifier of the thread. If equals zero, the identifier of the calling thread
will be used.

Stores priority for the given thread but doesn t actually change it to not mess up with test runner . Unlike real implementation does not throw any exceptions .


@Implementation
  protected static final int getThreadPriority(int tid) {
    if (tid == 0) {
      tid = ShadowProcess.myTid();
    }
    synchronized (threadPrioritiesLock) {
      return threadPriorities.getOrDefault(tid, 0);
    }
  }

@ Implementation protected static final int getThreadPriority ( int tid ) { if ( tid == 0 ) { tid = ShadowProcess . myTid ( ) ; } synchronized ( threadPrioritiesLock ) { return threadPriorities . getOrDefault ( tid , 0 ) ; } }

Returns priority stored for the given thread.

@param tid The identifier of the thread. If equals zero, the identifier of the calling thread
will be used.

Returns priority stored for the given thread .


int getIndexOfBit(int n) {
    // return __builtin_popcountll(value & ~(0xffffffffffffffffULL >> n));
    int numMarkedBits = 0;
    for (int i = 0; i < n; i++) {
      if (hasBit(i)) {
        numMarkedBits++;
      }
    }
    return numMarkedBits;
  }

Gets the index of the specified bit in the set, which is the number of marked bits that appear
before the specified bit.

Gets the index of the specified bit in the set which is the number of marked bits that appear before the specified bit .


@Implementation(minSdk = P)
  @HiddenApi
  @SystemApi
  @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
  public void setMode(String op, int uid, String packageName, int mode) {
    setMode(AppOpsManager.strOpToOp(op), uid, packageName, mode);
  }

@ Implementation ( minSdk = P ) @ HiddenApi @ SystemApi @ RequiresPermission ( android . Manifest . permission . MANAGE_APP_OPS_MODES ) public void setMode ( String op , int uid , String packageName , int mode ) { setMode ( AppOpsManager . strOpToOp ( op ) , uid , packageName , mode ) ; }

Change the operating mode for the given op in the given app package. You must pass in both the
uid and name of the application whose mode is being modified; if these do not match, the
modification will not be applied.

<p>This method is public for testing {@link #checkOpNoThrow}. If {@link #checkOpNoThrow} is
called afterwards with the {@code op}, {@code ui}, and {@code packageName} provided, it will
return the {@code mode} set here.

@param op The operation to modify. One of the OPSTR_* constants.
@param uid The user id of the application whose mode will be changed.
@param packageName The name of the application package name whose mode will be changed.

Change the operating mode for the given op in the given app package . You must pass in both the uid and name of the application whose mode is being modified ; if these do not match the modification will not be applied .


public static int getColor(String value) {
    if (value != null) {
      if (value.startsWith("#") == false) {
        throw new NumberFormatException(
            String.format("Color value '%s' must start with #", value));
      }

      value = value.substring(1);

      // make sure it's not longer than 32bit
      if (value.length() > 8) {
        throw new NumberFormatException(String.format(
            "Color value '%s' is too long. Format is either" +
            "#AARRGGBB, #RRGGBB, #RGB, or #ARGB",
            value));
      }

      if (value.length() == 3) { // RGB format
        char[] color = new char[8];
        color[0] = color[1] = 'F';
        color[2] = color[3] = value.charAt(0);
        color[4] = color[5] = value.charAt(1);
        color[6] = color[7] = value.charAt(2);
        value = new String(color);
      } else if (value.length() == 4) { // ARGB format
        char[] color = new char[8];
        color[0] = color[1] = value.charAt(0);
        color[2] = color[3] = value.charAt(1);
        color[4] = color[5] = value.charAt(2);
        color[6] = color[7] = value.charAt(3);
        value = new String(color);
      } else if (value.length() == 6) {
        value = "FF" + value;
      }

      // this is a RRGGBB or AARRGGBB value

      // Integer.parseInt will fail to inferFromValue strings like "ff191919", so we use
      // a Long, but cast the result back into an int, since we know that we're only
      // dealing with 32 bit values.
      return (int)Long.parseLong(value, 16);
    }

    throw new NumberFormatException();
  }

Returns the color value represented by the given string value

@param value the color value
@return the color as an int
@throws NumberFormatException if the conversion failed.


public static int getColorType(String value) {
    if (value != null && value.startsWith("#")) {
      switch (value.length()) {
        case 4:
          return TypedValue.TYPE_INT_COLOR_RGB4;
        case 5:
          return TypedValue.TYPE_INT_COLOR_ARGB4;
        case 7:
          return TypedValue.TYPE_INT_COLOR_RGB8;
        case 9:
          return TypedValue.TYPE_INT_COLOR_ARGB8;
      }
    }
    return TypedValue.TYPE_INT_COLOR_ARGB8;
  }

public static int getColorType ( String value ) { if ( value != null && value . startsWith ( "#" ) ) { switch ( value . length ( ) ) { case 4 : return TypedValue . TYPE_INT_COLOR_RGB4 ; case 5 : return TypedValue . TYPE_INT_COLOR_ARGB4 ; case 7 : return TypedValue . TYPE_INT_COLOR_RGB8 ; case 9 : return TypedValue . TYPE_INT_COLOR_ARGB8 ; } } return TypedValue . TYPE_INT_COLOR_ARGB8 ; }

Returns the TypedValue color type represented by the given string value

@param value the color value
@return the color as an int. For backwards compatibility, will return a default of ARGB8 if
value format is unrecognized.


public static boolean parseFloatAttribute(String attribute, String value,
      TypedValue outValue, boolean requireUnit) {
    assert requireUnit == false || attribute != null;

    // remove the space before and after
    value = value.trim();
    int len = value.length();

    if (len <= 0) {
      return false;
    }

    // check that there's no non ascii characters.
    char[] buf = value.toCharArray();
    for (int i = 0 ; i < len ; i++) {
      if (buf[i] > 255) {
        return false;
      }
    }

    // check the first character
    if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.' && buf[0] != '-') {
      return false;
    }

    // now look for the string that is after the float...
    Matcher m = sFloatPattern.matcher(value);
    if (m.matches()) {
      String f_str = m.group(1);
      String end = m.group(2);

      float f;
      try {
        f = Float.parseFloat(f_str);
      } catch (NumberFormatException e) {
        // this shouldn't happen with the regexp above.
        return false;
      }

      if (end.length() > 0 && end.charAt(0) != ' ') {
        // Might be a unit...
        if (parseUnit(end, outValue, sFloatOut)) {
          computeTypedValue(outValue, f, sFloatOut[0]);
          return true;
        }
        return false;
      }

      // make sure it's only spaces at the end.
      end = end.trim();

      if (end.length() == 0) {
        if (outValue != null) {
          outValue.assetCookie = 0;
          outValue.string = null;

          if (requireUnit == false) {
            outValue.type = TypedValue.TYPE_FLOAT;
            outValue.data = Float.floatToIntBits(f);
          } else {
            // no unit when required? Use dp and out an error.
            applyUnit(sUnitNames[1], outValue, sFloatOut);
            computeTypedValue(outValue, f, sFloatOut[0]);

            System.out.println(String.format(
                "Dimension \"%1$s\" in attribute \"%2$s\" is missing unit!",
                    value, attribute));
          }
          return true;
        }
      }
    }

    return false;
  }

Parse a float attribute and return the parsed value into a given TypedValue.
@param attribute the name of the attribute. Can be null if <var>requireUnit</var> is false.
@param value the string value of the attribute
@param outValue the TypedValue to receive the parsed value
@param requireUnit whether the value is expected to contain a unit.
@return true if success.

Parse a float attribute and return the parsed value into a given TypedValue .


@Implementation
  protected static ImageDecoder nCreate(long asset, Source source) throws IOException {
    return ImageDecoder_nCreateAsset(asset, source);
  }

@ Implementation protected static ImageDecoder nCreate ( long asset , Source source ) throws IOException { return ImageDecoder_nCreateAsset ( asset , source ) ; }


@Implementation
  protected static ImageDecoder nCreate(FileDescriptor fd, Source src) throws IOException {
    return ImageDecoder_nCreateFd(fd, src);
  }

@ Implementation protected static ImageDecoder nCreate ( FileDescriptor fd , Source src ) throws IOException { return ImageDecoder_nCreateFd ( fd , src ) ; }


public boolean clickMenuItem(int menuItemResId) {
    final RoboMenuItem item = new RoboMenuItem(menuItemResId);
    return realActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item);
  }

public boolean clickMenuItem ( int menuItemResId ) { final RoboMenuItem item = new RoboMenuItem ( menuItemResId ) ; return realActivity . onMenuItemSelected ( Window . FEATURE_OPTIONS_PANEL , item ) ; }

Perform a click on a menu item.

@param menuItemResId Menu item resource ID.
@return True if the click was handled, false otherwise.


public void callOnActivityResult(int requestCode, int resultCode, Intent resultData) {
    final ActivityInvoker invoker = new ActivityInvoker();
    invoker
        .call("onActivityResult", Integer.TYPE, Integer.TYPE, Intent.class)
        .with(requestCode, resultCode, resultData);
  }

public void callOnActivityResult ( int requestCode , int resultCode , Intent resultData ) { final ActivityInvoker invoker = new ActivityInvoker ( ) ; invoker . call ( "onActivityResult" , Integer . TYPE , Integer . TYPE , Intent . class ) . with ( requestCode , resultCode , resultData ) ; }

For internal use only. Not for public use.

For internal use only . Not for public use .


@Implementation(minSdk = LOLLIPOP)
  protected void startLockTask() {
    Shadow.<ShadowActivityManager>extract(getActivityManager())
        .setLockTaskModeState(ActivityManager.LOCK_TASK_MODE_LOCKED);
  }

@ Implementation ( minSdk = LOLLIPOP ) protected void startLockTask ( ) { Shadow . < ShadowActivityManager > extract ( getActivityManager ( ) ) . setLockTaskModeState ( ActivityManager . LOCK_TASK_MODE_LOCKED ) ; }

Starts a lock task.

<p>The status of the lock task can be verified using {@link #isLockTask} method. Otherwise this
implementation has no effect.


@Implementation(minSdk = LOLLIPOP)
  protected void stopLockTask() {
    Shadow.<ShadowActivityManager>extract(getActivityManager())
        .setLockTaskModeState(ActivityManager.LOCK_TASK_MODE_NONE);
  }

@ Implementation ( minSdk = LOLLIPOP ) protected void stopLockTask ( ) { Shadow . < ShadowActivityManager > extract ( getActivityManager ( ) ) . setLockTaskModeState ( ActivityManager . LOCK_TASK_MODE_NONE ) ; }

Stops a lock task.

<p>The status of the lock task can be verified using {@link #isLockTask} method. Otherwise this
implementation has no effect.


public synchronized void postDelayed(Runnable runnable, long delay, TimeUnit unit) {
    long delayMillis = unit.toMillis(delay);
    if ((idleState != CONSTANT_IDLE && (isPaused() || delayMillis > 0)) || Thread.currentThread() != associatedThread) {
      runnables.add(new ScheduledRunnable(runnable, currentTime + delayMillis));
    } else {
      runOrQueueRunnable(runnable, currentTime + delayMillis);
    }
  }

public synchronized void postDelayed ( Runnable runnable , long delay , TimeUnit unit ) { long delayMillis = unit . toMillis ( delay ) ; if ( ( idleState != CONSTANT_IDLE && ( isPaused ( ) || delayMillis > 0 ) ) || Thread . currentThread ( ) != associatedThread ) { runnables . add ( new ScheduledRunnable ( runnable , currentTime + delayMillis ) ) ; } else { runOrQueueRunnable ( runnable , currentTime + delayMillis ) ; } }

Add a runnable to the queue to be run after a delay.

Add a runnable to the queue to be run after a delay .


public synchronized void postAtFrontOfQueue(Runnable runnable) {
    if (isPaused() || Thread.currentThread() != associatedThread) {
      final long timeDisambiguator;
      if (runnables.isEmpty()) {
        timeDisambiguator = nextTimeDisambiguator++;
      } else {
        timeDisambiguator = runnables.peek().timeDisambiguator - 1;
      }
      runnables.add(new ScheduledRunnable(runnable, 0, timeDisambiguator));
    } else {
      runOrQueueRunnable(runnable, currentTime);
    }
  }

public synchronized void postAtFrontOfQueue ( Runnable runnable ) { if ( isPaused ( ) || Thread . currentThread ( ) != associatedThread ) { final long timeDisambiguator ; if ( runnables . isEmpty ( ) ) { timeDisambiguator = nextTimeDisambiguator ++ ; } else { timeDisambiguator = runnables . peek ( ) . timeDisambiguator - 1 ; } runnables . add ( new ScheduledRunnable ( runnable , 0 , timeDisambiguator ) ) ; } else { runOrQueueRunnable ( runnable , currentTime ) ; } }

Add a runnable to the head of the queue.

@param runnable  Runnable to add.

Add a runnable to the head of the queue .


public synchronized void remove(Runnable runnable) {
    Iterator<ScheduledRunnable> iterator = runnables.iterator();
    while (iterator.hasNext()) {
      if (iterator.next().runnable == runnable) {
        iterator.remove();
      }
    }
  }

public synchronized void remove ( Runnable runnable ) { Iterator < ScheduledRunnable > iterator = runnables . iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( iterator . next ( ) . runnable == runnable ) { iterator . remove ( ) ; } } }

Remove a runnable from the queue.

@param runnable  Runnable to remove.


public synchronized boolean advanceToLastPostedRunnable() {
    long currentMaxTime = currentTime;
    for (ScheduledRunnable scheduled : runnables) {
      if (currentMaxTime < scheduled.scheduledTime) {
        currentMaxTime = scheduled.scheduledTime;
      }
    }
    return advanceTo(currentMaxTime);
  }

public synchronized boolean advanceToLastPostedRunnable ( ) { long currentMaxTime = currentTime ; for ( ScheduledRunnable scheduled : runnables ) { if ( currentMaxTime < scheduled . scheduledTime ) { currentMaxTime = scheduled . scheduledTime ; } } return advanceTo ( currentMaxTime ) ; }

Run all runnables in the queue, and any additional runnables they schedule that are scheduled
before the latest scheduled runnable currently in the queue.

@return True if a runnable was executed.

Run all runnables in the queue and any additional runnables they schedule that are scheduled before the latest scheduled runnable currently in the queue .


public synchronized boolean advanceBy(long amount, TimeUnit unit) {
    long endingTime = currentTime + unit.toMillis(amount);
    return advanceTo(endingTime);
  }

public synchronized boolean advanceBy ( long amount , TimeUnit unit ) { long endingTime = currentTime + unit . toMillis ( amount ) ; return advanceTo ( endingTime ) ; }

Run all runnables that are scheduled to run in the next time interval.

@return  True if a runnable was executed.

Run all runnables that are scheduled to run in the next time interval .


public synchronized boolean advanceTo(long endTime) {
    if (endTime < currentTime || runnables.isEmpty()) {
      currentTime = endTime;
      return false;
    }

    int runCount = 0;
    while (nextTaskIsScheduledBefore(endTime)) {
      runOneTask();
      ++runCount;
    }
    currentTime = endTime;
    return runCount > 0;
  }

public synchronized boolean advanceTo ( long endTime ) { if ( endTime < currentTime || runnables . isEmpty ( ) ) { currentTime = endTime ; return false ; } int runCount = 0 ; while ( nextTaskIsScheduledBefore ( endTime ) ) { runOneTask ( ) ; ++ runCount ; } currentTime = endTime ; return runCount > 0 ; }

Run all runnables that are scheduled before the endTime.

@param   endTime   Future time.
@return  True if a runnable was executed.

Run all runnables that are scheduled before the endTime .


public synchronized boolean runOneTask() {
    ScheduledRunnable postedRunnable = runnables.poll();
    if (postedRunnable != null) {
      if (postedRunnable.scheduledTime > currentTime) {
        currentTime = postedRunnable.scheduledTime;
      }
      postedRunnable.run();
      return true;
    }
    return false;
  }

public synchronized boolean runOneTask ( ) { ScheduledRunnable postedRunnable = runnables . poll ( ) ; if ( postedRunnable != null ) { if ( postedRunnable . scheduledTime > currentTime ) { currentTime = postedRunnable . scheduledTime ; } postedRunnable . run ( ) ; return true ; } return false ; }

Run the next runnable in the queue.

@return  True if a runnable was executed.


@Implementation(minSdk = LOLLIPOP)
  protected boolean bindServiceAsUser(
      Intent intent, final ServiceConnection serviceConnection, int i, UserHandle userHandle) {
    return getShadowInstrumentation().bindService(intent, serviceConnection, i);
  }

@ Implementation ( minSdk = LOLLIPOP ) protected boolean bindServiceAsUser ( Intent intent , final ServiceConnection serviceConnection , int i , UserHandle userHandle ) { return getShadowInstrumentation ( ) . bindService ( intent , serviceConnection , i ) ; }

Binds to a service but ignores the given UserHandle.

Binds to a service but ignores the given UserHandle .


@Implementation
  protected static boolean setCurrentTimeMillis(long millis) {
    if (currentTimeMillis > millis) {
      return false;
    }

    currentTimeMillis = millis;
    for (Listener listener : listeners) {
      listener.clockUpdated(currentTimeMillis);
    }
    return true;
  }

@ Implementation protected static boolean setCurrentTimeMillis ( long millis ) { if ( currentTimeMillis > millis ) { return false ; } currentTimeMillis = millis ; for ( Listener listener : listeners ) { listener . clockUpdated ( currentTimeMillis ) ; } return true ; }

Sets the current wall time.

<p>Currently does not perform any permission checks.

@return false if specified time is less than current time.


@Implementation(minSdk = 23)
  public boolean isIdle() {
    if (Build.VERSION.SDK_INT >= M) {
      return directlyOn(realQueue, MessageQueue.class).isIdle();
    } else {
      ReflectorMessageQueue internalQueue = reflector(ReflectorMessageQueue.class, realQueue);
      // this is a copy of the implementation from P
      synchronized (realQueue) {
        final long now = SystemClock.uptimeMillis();
        Message headMsg = internalQueue.getMessages();
        if (headMsg == null) {
          return true;
        }
        long when = shadowOfMsg(headMsg).getWhen();
        return now < when;
      }
    }
  }

Exposes the API23+_isIdle method to older platforms

Exposes the API23 + _isIdle method to older platforms


@Override
  public void reset() {
    ReflectorMessageQueue msgQueue = reflector(ReflectorMessageQueue.class, realQueue);
    msgQueue.setMessages(null);
    msgQueue.setIdleHandlers(new ArrayList<>());
    msgQueue.setNextBarrierToken(0);
  }

@ Override public void reset ( ) { ReflectorMessageQueue msgQueue = reflector ( ReflectorMessageQueue . class , realQueue ) ; msgQueue . setMessages ( null ) ; msgQueue . setIdleHandlers ( new ArrayList <> ( ) ) ; msgQueue . setNextBarrierToken ( 0 ) ; }


public static <T extends Activity> ActivityController<T> buildActivity(Class<T> activityClass) {
    return buildActivity(activityClass, null);
  }

public static < T extends Activity > ActivityController < T > buildActivity ( Class < T > activityClass ) { return buildActivity ( activityClass , null ) ; }

Creates a ActivityController for the given activity class.

<p>Consider using {@link androidx.test.core.app.ActivityScenario} instead, which provides
higher-level, streamlined APIs to control the lifecycle and it works with instrumentation tests
too.

Creates a ActivityController for the given activity class .


public static <T extends Activity> ActivityController<T> buildActivity(
      Class<T> activityClass, Intent intent) {
    return ActivityController.of(ReflectionHelpers.callConstructor(activityClass), intent);
  }

public static < T extends Activity > ActivityController < T > buildActivity ( Class < T > activityClass , Intent intent ) { return ActivityController . of ( ReflectionHelpers . callConstructor ( activityClass ) , intent ) ; }

Creates a ActivityController for the given activity class with the intent.

Note: the activity class is not determined by the intent.

Consider using {@link androidx.test.core.app.ActivityScenario} instead, which provides
higher-level, streamlined APIs to control the lifecycle and it works with instrumentation tests
too.

Creates a ActivityController for the given activity class with the intent .


@Deprecated
  public static <T extends Activity> T setupActivity(Class<T> activityClass) {
    return buildActivity(activityClass).setup().get();
  }

@ Deprecated public static < T extends Activity > T setupActivity ( Class < T > activityClass ) { return buildActivity ( activityClass ) . setup ( ) . get ( ) ; }

Simulates starting activity with the given class type and returns its reference.

<p>Use {@link androidx.test.core.app.ActivityScenario} instead, which works with
instrumentation tests too.

@deprecated use {@link androidx.test.core.app.ActivityScenario}

Simulates starting activity with the given class type and returns its reference .


@Deprecated
  public static <T extends Fragment> FragmentController<T> buildFragment(Class<T> fragmentClass) {
    return FragmentController.of(ReflectionHelpers.callConstructor(fragmentClass));
  }

@ Deprecated public static < T extends Fragment > FragmentController < T > buildFragment ( Class < T > fragmentClass ) { return FragmentController . of ( ReflectionHelpers . callConstructor ( fragmentClass ) ) ; }

Creates a FragmentController for the given fragment class.

<p>FragmentController provides low-level APIs to control its lifecycle. Please consider using
{@link androidx.fragment.app.testing.FragmentScenario} instead, which provides higher level
APIs and works with instrumentation tests too.

@deprecated Native Fragments have been deprecated in Android P. Android encourages developers
to use androidx fragments, to test these use FragmentScenario.

Creates a FragmentController for the given fragment class .


@Implementation
  protected int speak(
      final String text, final int queueMode, final HashMap<String, String> params) {
    if (RuntimeEnvironment.getApiLevel() >= LOLLIPOP) {
      return Shadow.directlyOn(tts, TextToSpeech.class).speak(text, queueMode, params);
    }
    return speak(
        text, queueMode, null, params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID));
  }

@ Implementation protected int speak ( final String text , final int queueMode , final HashMap < String , String > params ) { if ( RuntimeEnvironment . getApiLevel ( ) >= LOLLIPOP ) { return Shadow . directlyOn ( tts , TextToSpeech . class ) . speak ( text , queueMode , params ) ; } return speak ( text , queueMode , null , params == null ? null : params . get ( Engine . KEY_PARAM_UTTERANCE_ID ) ) ; }

Speaks the string using the specified queuing strategy and speech parameters.

@param params The real implementation converts the hashmap into a bundle, but the bundle
argument is not used in the shadow implementation.

Speaks the string using the specified queuing strategy and speech parameters .


@Implementation(minSdk = O_MR1)
  public Point getStableDisplaySize() throws RemoteException {
    DisplayInfo defaultDisplayInfo = mDm.getDisplayInfo(Display.DEFAULT_DISPLAY);
    return new Point(defaultDisplayInfo.getNaturalWidth(), defaultDisplayInfo.getNaturalHeight());
  }

@ Implementation ( minSdk = O_MR1 ) public Point getStableDisplaySize ( ) throws RemoteException { DisplayInfo defaultDisplayInfo = mDm . getDisplayInfo ( Display . DEFAULT_DISPLAY ) ; return new Point ( defaultDisplayInfo . getNaturalWidth ( ) , defaultDisplayInfo . getNaturalHeight ( ) ) ; }

Returns the 'natural' dimensions of the default display.

Returns the natural dimensions of the default display .


private static FileSystem getJarFs(Path jarFile) throws IOException {
    Path key = jarFile.toAbsolutePath();

    synchronized (ZIP_FILESYSTEMS) {
      FsWrapper fs = ZIP_FILESYSTEMS.get(key);
      if (fs == null) {
        fs = new FsWrapper(FileSystems.newFileSystem(key, null), key);
        fs.incrRefCount();

        ZIP_FILESYSTEMS.put(key, fs);
      } else {
        fs.incrRefCount();
      }

      return fs;
    }
  }

private static FileSystem getJarFs ( Path jarFile ) throws IOException { Path key = jarFile . toAbsolutePath ( ) ; synchronized ( ZIP_FILESYSTEMS ) { FsWrapper fs = ZIP_FILESYSTEMS . get ( key ) ; if ( fs == null ) { fs = new FsWrapper ( FileSystems . newFileSystem ( key , null ) , key ) ; fs . incrRefCount ( ) ; ZIP_FILESYSTEMS . put ( key , fs ) ; } else { fs . incrRefCount ( ) ; } return fs ; } }

Returns a reference-counted Jar FileSystem, possibly one that was previously returned.

Returns a reference - counted Jar FileSystem possibly one that was previously returned .


public static List<LogItem> getLogsForTag(String tag) {
    Queue<LogItem> logs = logsByTag.get(tag);
    return logs == null ? Collections.emptyList() : new ArrayList<>(logs);
  }

public static List < LogItem > getLogsForTag ( String tag ) { Queue < LogItem > logs = logsByTag . get ( tag ) ; return logs == null ? Collections . emptyList ( ) : new ArrayList <> ( logs ) ; }

Returns ordered list of all log items for a specific tag.

@param tag The tag to get logs for
@return The list of log items for the tag or an empty list if no logs for that tag exist.

Returns ordered list of all log items for a specific tag .


public List<AndroidManifest> getAllManifests() {
    Set<AndroidManifest> seenManifests = new HashSet<>();
    List<AndroidManifest> uniqueManifests = new ArrayList<>();
    addTransitiveManifests(seenManifests, uniqueManifests);
    return uniqueManifests;
  }

public List < AndroidManifest > getAllManifests ( ) { Set < AndroidManifest > seenManifests = new HashSet <> ( ) ; List < AndroidManifest > uniqueManifests = new ArrayList <> ( ) ; addTransitiveManifests ( seenManifests , uniqueManifests ) ; return uniqueManifests ; }

Returns all transitively reachable manifests, including this one, in order and without
duplicates.

Returns all transitively reachable manifests including this one in order and without duplicates .


public @Nullable BroadcastReceiverData getBroadcastReceiver(String className) {
    parseAndroidManifest();
    for (BroadcastReceiverData receiver : receivers) {
      if (receiver.getName().equals(className)) {
        return receiver;
      }
    }
    return null;
  }

public @ Nullable BroadcastReceiverData getBroadcastReceiver ( String className ) { parseAndroidManifest ( ) ; for ( BroadcastReceiverData receiver : receivers ) { if ( receiver . getName ( ) . equals ( className ) ) { return receiver ; } } return null ; }

Returns data for the broadcast receiver with the provided name from this manifest. If no
receiver with the class name can be found, returns null.

@param className the fully resolved class name of the receiver
@return data for the receiver or null if it cannot be found

Returns data for the broadcast receiver with the provided name from this manifest . If no receiver with the class name can be found returns null .


@Implementation(minSdk = Build.VERSION_CODES.O)
  protected void deleteNotificationChannelGroup(String channelGroupId) {
    if (getNotificationChannelGroup(channelGroupId) != null) {
      // Deleting a channel group also deleted all associated channels. See
      // https://developer.android.com/reference/android/app/NotificationManager.html#deleteNotificationChannelGroup%28java.lang.String%29
      // for more info.
      for (/* NotificationChannel */ Object channel : getNotificationChannels()) {
        String groupId = ReflectionHelpers.callInstanceMethod(channel, "getGroup");
        if (channelGroupId.equals(groupId)) {
          String channelId = ReflectionHelpers.callInstanceMethod(channel, "getId");
          deleteNotificationChannel(channelId);
        }
      }
      notificationChannelGroups.remove(channelGroupId);
    }
  }

Delete a notification channel group and all notification channels associated with the group.
This method will not notify any NotificationListenerService of resulting changes to
notification channel groups nor to notification channels.

Delete a notification channel group and all notification channels associated with the group . This method will not notify any NotificationListenerService of resulting changes to notification channel groups nor to notification channels .


private static int getJavaVersion() {
    String version = System.getProperty("java.version");
    assert version != null;
    if (version.startsWith("1.")) {
      version = version.substring(2);
    }
    // Allow these formats:
    // 1.8.0_72-ea
    // 9-ea
    // 9
    // 9.0.1
    int dotPos = version.indexOf('.');
    int dashPos = version.indexOf('-');
    return Integer.parseInt(
        version.substring(0, dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1));
  }

private
static
int
getJavaVersion
(
)
{
String
version
=
System
.
getProperty
(
"java.version"
)
;
assert
version
!=
;
if
(
version
.
startsWith
(
"1."
)
)
{
version
=
version
.
substring
(
2
)
;
}
// Allow these formats:
// 1.8.0_72-ea
// 9-ea
// 9
// 9.0.1
int
dotPos
=
version
.
indexOf
(
'
'
)
;
int
dashPos
=
version
.
indexOf
(
'
'
)
;
return
Integer
.
parseInt
(
version
.
substring
(
0
,
dotPos
>
1
dotPos
:
dashPos
>
1
dashPos
:
1
)
)
;
}

Returns the Java version as an int value.

@return the Java version as an int value (8, 9, etc.)

Returns the Java version as an int value .


@Implementation
  protected final void transform(Matrix matrix) {
    checkNotNull(matrix);
    NativeInput.MotionEvent event = getNativeMotionEvent();
    ShadowMatrix shadowMatrix = Shadow.extract(matrix);

    float[] m = new float[9];
    shadowMatrix.getValues(m);
    event.transform(m);
  }

@ Implementation protected final void transform ( Matrix matrix ) { checkNotNull ( matrix ) ; NativeInput . MotionEvent event = getNativeMotionEvent ( ) ; ShadowMatrix shadowMatrix = Shadow . extract ( matrix ) ; float [ ] m = new float [ 9 ] ; shadowMatrix . getValues ( m ) ; event . transform ( m ) ; }

shadow this directly as opposed to nativeTransform because need access to ShadowMatrix


@Implementation
  @Nullable
  @SuppressWarnings("unchecked")
  protected <T> T get(Key<T> key) {
    return (T) resultsKeyToValue.get(key);
  }

@ Implementation @ Nullable @ SuppressWarnings ( "unchecked" ) protected < T > T get ( Key < T > key ) { return ( T ) resultsKeyToValue . get ( key ) ; }

Obtain a property of the CaptureResult .


@Implementation @HiddenApi
  protected final int loadResourceBagValue(int ident, int bagEntryId, TypedValue outValue,
      boolean resolve) {
    CppAssetManager am = assetManagerForJavaObject();
    if (am == null) {
      return 0;
    }
    final ResTable res = am.getResources();
    return loadResourceBagValueInternal(ident, bagEntryId, outValue, resolve, res);
  }

@ Implementation @ HiddenApi protected final int loadResourceBagValue ( int ident , int bagEntryId , TypedValue outValue , boolean resolve ) { CppAssetManager am = assetManagerForJavaObject ( ) ; if ( am == null ) { return 0 ; } final ResTable res = am . getResources ( ) ; return loadResourceBagValueInternal ( ident , bagEntryId , outValue , resolve , res ) ; }

Returns true if the resource was found, filling in mRetStringBlock and
mRetData.

Returns true if the resource was found filling in mRetStringBlock and mRetData .


@Override
  @Deprecated
  public boolean post(Runnable runnable, long delayMillis) {
    if (!quit) {
      getScheduler().postDelayed(runnable, delayMillis, TimeUnit.MILLISECONDS);
      return true;
    } else {
      return false;
    }
  }

@ Override @ Deprecated public boolean post ( Runnable runnable , long delayMillis ) { if ( ! quit ) { getScheduler ( ) . postDelayed ( runnable , delayMillis , TimeUnit . MILLISECONDS ) ; return true ; } else { return false ; } }

Enqueue a task to be run later.

@param runnable    the task to be run
@param delayMillis how many milliseconds into the (virtual) future to run it
@return true if the runnable is enqueued
@see android.os.Handler#postDelayed(Runnable,long)
@deprecated Use a {@link android.os.Handler} instance to post to a looper.


@Override
  @Deprecated
  public boolean postAtFrontOfQueue(Runnable runnable) {
    if (!quit) {
      getScheduler().postAtFrontOfQueue(runnable);
      return true;
    } else {
      return false;
    }
  }

@ Override @ Deprecated public boolean postAtFrontOfQueue ( Runnable runnable ) { if ( ! quit ) { getScheduler ( ) . postAtFrontOfQueue ( runnable ) ; return true ; } else { return false ; } }

Enqueue a task to be run ahead of all other delayed tasks.

@param runnable    the task to be run
@return true if the runnable is enqueued
@see android.os.Handler#postAtFrontOfQueue(Runnable)
@deprecated Use a {@link android.os.Handler} instance to post to a looper.

Enqueue a task to be run ahead of all other delayed tasks .


public ActivityInfo addActivityIfNotPresent(ComponentName componentName) {
    return addComponent(
        activityFilters,
        p -> p.activities,
        (p, a) -> p.activities = a,
        updateName(componentName, new ActivityInfo()),
        false);
  }

public ActivityInfo addActivityIfNotPresent ( ComponentName componentName ) { return addComponent ( activityFilters , p -> p . activities , ( p , a ) -> p . activities = a , updateName ( componentName , new ActivityInfo ( ) ) , false ) ; }

Makes sure that given activity exists.

If the activity doesn't exist yet, it will be created with {@code applicationInfo} set to an
existing application, or if it doesn't exist, a new package will be created.

@return existing or newly created activity info.


public ServiceInfo addServiceIfNotPresent(ComponentName componentName) {
    return addComponent(
        serviceFilters,
        p -> p.services,
        (p, a) -> p.services = a,
        updateName(componentName, new ServiceInfo()),
        false);
  }

public ServiceInfo addServiceIfNotPresent ( ComponentName componentName ) { return addComponent ( serviceFilters , p -> p . services , ( p , a ) -> p . services = a , updateName ( componentName , new ServiceInfo ( ) ) , false ) ; }

Makes sure that given service exists.

If the service doesn't exist yet, it will be created with {@code applicationInfo} set to an
existing application, or if it doesn't exist, a new package will be created.

@return existing or newly created service info.


public ActivityInfo addReceiverIfNotPresent(ComponentName componentName) {
    return addComponent(
        receiverFilters,
        p -> p.receivers,
        (p, a) -> p.receivers = a,
        updateName(componentName, new ActivityInfo()),
        false);
  }

public ActivityInfo addReceiverIfNotPresent ( ComponentName componentName ) { return addComponent ( receiverFilters , p -> p . receivers , ( p , a ) -> p . receivers = a , updateName ( componentName , new ActivityInfo ( ) ) , false ) ; }

Makes sure that given receiver exists.

If the receiver doesn't exist yet, it will be created with {@code applicationInfo} set to an
existing application, or if it doesn't exist, a new package will be created.

@return existing or newly created receiver info.


public ProviderInfo addProviderIfNotPresent(ComponentName componentName) {
    return addComponent(
        providerFilters,
        p -> p.providers,
        (p, a) -> p.providers = a,
        updateName(componentName, new ProviderInfo()),
        false);
  }

public ProviderInfo addProviderIfNotPresent ( ComponentName componentName ) { return addComponent ( providerFilters , p -> p . providers , ( p , a ) -> p . providers = a , updateName ( componentName , new ProviderInfo ( ) ) , false ) ; }

Makes sure that given provider exists.

If the provider doesn't exist yet, it will be created with {@code applicationInfo} set to an
existing application, or if it doesn't exist, a new package will be created.

@return existing or newly created provider info.


public void addOrUpdateActivity(ActivityInfo activityInfo) {
    addComponent(
        activityFilters,
        p -> p.activities,
        (p, a) -> p.activities = a,
        new ActivityInfo(activityInfo),
        true);
  }

public void addOrUpdateActivity ( ActivityInfo activityInfo ) { addComponent ( activityFilters , p -> p . activities , ( p , a ) -> p . activities = a , new ActivityInfo ( activityInfo ) , true ) ; }

Adds or updates given activity in the system.

If activity with the same {@link ComponentInfo#name} and {@code ComponentInfo#packageName}
exists it will be updated. Its {@link ComponentInfo#applicationInfo} is always set to {@link
ApplicationInfo} already existing in the system, but if no application exists a new one will
be created using {@link ComponentInfo#applicationInfo} in this component.

Adds or updates given activity in the system .


public void addOrUpdateService(ServiceInfo serviceInfo) {
    addComponent(
        serviceFilters,
        p -> p.services,
        (p, a) -> p.services = a,
        new ServiceInfo(serviceInfo),
        true);
  }

public void addOrUpdateService ( ServiceInfo serviceInfo ) { addComponent ( serviceFilters , p -> p . services , ( p , a ) -> p . services = a , new ServiceInfo ( serviceInfo ) , true ) ; }

Adds or updates given service in the system.

If service with the same {@link ComponentInfo#name} and {@code ComponentInfo#packageName}
exists it will be updated. Its {@link ComponentInfo#applicationInfo} is always set to {@link
ApplicationInfo} already existing in the system, but if no application exists a new one will be
created using {@link ComponentInfo#applicationInfo} in this component.

Adds or updates given service in the system .


public void addOrUpdateReceiver(ActivityInfo receiverInfo) {
    addComponent(
        receiverFilters,
        p -> p.receivers,
        (p, a) -> p.receivers = a,
        new ActivityInfo(receiverInfo),
        true);
  }

public void addOrUpdateReceiver ( ActivityInfo receiverInfo ) { addComponent ( receiverFilters , p -> p . receivers , ( p , a ) -> p . receivers = a , new ActivityInfo ( receiverInfo ) , true ) ; }

Adds or updates given broadcast receiver in the system.

If broadcast receiver with the same {@link ComponentInfo#name} and {@code
ComponentInfo#packageName} exists it will be updated. Its {@link ComponentInfo#applicationInfo}
is always set to {@link ApplicationInfo} already existing in the system, but if no
application exists a new one will be created using {@link ComponentInfo#applicationInfo} in
this component.

Adds or updates given broadcast receiver in the system .


public void addOrUpdateProvider(ProviderInfo providerInfo) {
    addComponent(
        providerFilters,
        p -> p.providers,
        (p, a) -> p.providers = a,
        new ProviderInfo(providerInfo),
        true);
  }

public void addOrUpdateProvider ( ProviderInfo providerInfo ) { addComponent ( providerFilters , p -> p . providers , ( p , a ) -> p . providers = a , new ProviderInfo ( providerInfo ) , true ) ; }

Adds or updates given content provider in the system.

If content provider with the same {@link ComponentInfo#name} and {@code
ComponentInfo#packageName} exists it will be updated. Its {@link ComponentInfo#applicationInfo}
is always set to {@link ApplicationInfo} already existing in the system, but if no
application exists a new one will be created using {@link ComponentInfo#applicationInfo} in
this component.

Adds or updates given content provider in the system .


@Nullable
  public ActivityInfo removeActivity(ComponentName componentName) {
    return removeComponent(
        componentName, activityFilters, p -> p.activities, (p, a) -> p.activities = a);
  }

@ Nullable public ActivityInfo removeActivity ( ComponentName componentName ) { return removeComponent ( componentName , activityFilters , p -> p . activities , ( p , a ) -> p . activities = a ) ; }

Removes activity from the package manager.

@return the removed component or {@code null} if no such component existed.

Removes activity from the package manager .


@Nullable
  public ServiceInfo removeService(ComponentName componentName) {
    return removeComponent(
        componentName, serviceFilters, p -> p.services, (p, a) -> p.services = a);
  }

@ Nullable public ServiceInfo removeService ( ComponentName componentName ) { return removeComponent ( componentName , serviceFilters , p -> p . services , ( p , a ) -> p . services = a ) ; }

Removes service from the package manager.

@return the removed component or {@code null} if no such component existed.

Removes service from the package manager .


@Nullable
  public ProviderInfo removeProvider(ComponentName componentName) {
    return removeComponent(
        componentName, providerFilters, p -> p.providers, (p, a) -> p.providers = a);
  }

@ Nullable public ProviderInfo removeProvider ( ComponentName componentName ) { return removeComponent ( componentName , providerFilters , p -> p . providers , ( p , a ) -> p . providers = a ) ; }

Removes content provider from the package manager.

@return the removed component or {@code null} if no such component existed.

Removes content provider from the package manager .


@Nullable
  public ActivityInfo removeReceiver(ComponentName componentName) {
    return removeComponent(
        componentName, receiverFilters, p -> p.receivers, (p, a) -> p.receivers = a);
  }

@ Nullable public ActivityInfo removeReceiver ( ComponentName componentName ) { return removeComponent ( componentName , receiverFilters , p -> p . receivers , ( p , a ) -> p . receivers = a ) ; }

Removes broadcast receiver from the package manager.

@return the removed component or {@code null} if no such component existed.

Removes broadcast receiver from the package manager .


@Deprecated
  public void setResolveInfosForIntent(Intent intent, List<ResolveInfo> info) {
    resolveInfoForIntent.remove(intent);
    for (ResolveInfo resolveInfo : info) {
      addResolveInfoForIntent(intent, resolveInfo);
    }
  }

@ Deprecated public void setResolveInfosForIntent ( Intent intent , List < ResolveInfo > info ) { resolveInfoForIntent . remove ( intent ) ; for ( ResolveInfo resolveInfo : info ) { addResolveInfoForIntent ( intent , resolveInfo ) ; } }

Sets extra resolve infos for an intent.

Those entries are added to whatever might be in the manifest already.

Note that all resolve infos will have {@link ResolveInfo#isDefault} field set to {@code
true} to allow their resolution for implicit intents. If this is not what you want, then you
still have the reference to those ResolveInfos, and you can set the field back to {@code
false}.

@deprecated see the note on {@link #addResolveInfoForIntent(Intent, ResolveInfo)}.

Sets extra resolve infos for an intent .


@Deprecated
  public void addResolveInfoForIntent(Intent intent, ResolveInfo info) {
    info.isDefault = true;
    ComponentInfo[] componentInfos =
        new ComponentInfo[] {
          info.activityInfo,
          info.serviceInfo,
          Build.VERSION.SDK_INT >= KITKAT ? info.providerInfo : null
        };
    for (ComponentInfo component : componentInfos) {
      if (component != null && component.applicationInfo != null) {
        component.applicationInfo.flags |= ApplicationInfo.FLAG_INSTALLED;
        if (component.applicationInfo.processName == null) {
          component.applicationInfo.processName = component.applicationInfo.packageName;
        }
      }
    }
    if (info.match == 0) {
      info.match = Integer.MAX_VALUE; // make sure, that this is as good match as possible.
    }
    addResolveInfoForIntentNoDefaults(intent, info);
  }

Adds extra resolve info for an intent.

Note that this resolve info will have {@link ResolveInfo#isDefault} field set to {@code
true} to allow its resolution for implicit intents. If this is not what you want, then please
use {@link #addResolveInfoForIntentNoDefaults} instead.

@deprecated use {@link #addIntentFilterForComponent} instead and if the component doesn't exist
add it using any of {@link #installPackage}, {@link #addOrUpdateActivity}, {@link
#addActivityIfNotPresent} or their counterparts for other types of components.


public void addPackageInternal(Package appPackage) {
    int flags =
        GET_ACTIVITIES
            | GET_RECEIVERS
            | GET_SERVICES
            | GET_PROVIDERS
            | GET_INSTRUMENTATION
            | GET_INTENT_FILTERS
            | GET_SIGNATURES
            | GET_RESOLVED_FILTER
            | GET_META_DATA
            | GET_GIDS
            | MATCH_DISABLED_COMPONENTS
            | GET_SHARED_LIBRARY_FILES
            | GET_URI_PERMISSION_PATTERNS
            | GET_PERMISSIONS
            | MATCH_UNINSTALLED_PACKAGES
            | GET_CONFIGURATIONS
            | MATCH_DISABLED_UNTIL_USED_COMPONENTS
            | MATCH_DIRECT_BOOT_UNAWARE
            | MATCH_DIRECT_BOOT_AWARE;

    for (PermissionGroup permissionGroup : appPackage.permissionGroups) {
      PermissionGroupInfo permissionGroupInfo =
          PackageParser.generatePermissionGroupInfo(permissionGroup, flags);
      addPermissionGroupInfo(permissionGroupInfo);
    }
    PackageInfo packageInfo =
        reflector(_PackageParser_.class)
            .generatePackageInfo(appPackage, new int[] {0}, flags, 0, 0);

    packageInfo.applicationInfo.uid = Process.myUid();
    packageInfo.applicationInfo.dataDir = createTempDir(packageInfo.packageName + "-dataDir");
    installPackage(packageInfo);
    addFilters(activityFilters, appPackage.activities);
    addFilters(serviceFilters, appPackage.services);
    addFilters(providerFilters, appPackage.providers);
    addFilters(receiverFilters, appPackage.receivers);
  }

public void addPackageInternal ( Package appPackage ) { int flags = GET_ACTIVITIES | GET_RECEIVERS | GET_SERVICES | GET_PROVIDERS | GET_INSTRUMENTATION | GET_INTENT_FILTERS | GET_SIGNATURES | GET_RESOLVED_FILTER | GET_META_DATA | GET_GIDS | MATCH_DISABLED_COMPONENTS | GET_SHARED_LIBRARY_FILES | GET_URI_PERMISSION_PATTERNS | GET_PERMISSIONS | MATCH_UNINSTALLED_PACKAGES | GET_CONFIGURATIONS | MATCH_DISABLED_UNTIL_USED_COMPONENTS | MATCH_DIRECT_BOOT_UNAWARE | MATCH_DIRECT_BOOT_AWARE ; for ( PermissionGroup permissionGroup : appPackage . permissionGroups ) { PermissionGroupInfo permissionGroupInfo = PackageParser . generatePermissionGroupInfo ( permissionGroup , flags ) ; addPermissionGroupInfo ( permissionGroupInfo ) ; } PackageInfo packageInfo = reflector ( _PackageParser_ . class ) . generatePackageInfo ( appPackage , new int [ ] { 0 } , flags , 0 , 0 ) ; packageInfo . applicationInfo . uid = Process . myUid ( ) ; packageInfo . applicationInfo . dataDir = createTempDir ( packageInfo . packageName + "-dataDir" ) ; installPackage ( packageInfo ) ; addFilters ( activityFilters , appPackage . activities ) ; addFilters ( serviceFilters , appPackage . services ) ; addFilters ( providerFilters , appPackage . providers ) ; addFilters ( receiverFilters , appPackage . receivers ) ; }


public void addIntentFilterForActivity(ComponentName componentName, IntentFilter filter)
      throws NameNotFoundException {
    addIntentFilterForComponent(componentName, filter, activityFilters);
  }

public void addIntentFilterForActivity ( ComponentName componentName , IntentFilter filter ) throws NameNotFoundException { addIntentFilterForComponent ( componentName , filter , activityFilters ) ; }

Add intent filter for given activity.

@throws NameNotFoundException if component with given name doesn't exist.


public void addIntentFilterForService(ComponentName componentName, IntentFilter filter)
      throws NameNotFoundException {
    addIntentFilterForComponent(componentName, filter, serviceFilters);
  }

public void addIntentFilterForService ( ComponentName componentName , IntentFilter filter ) throws NameNotFoundException { addIntentFilterForComponent ( componentName , filter , serviceFilters ) ; }

Add intent filter for given service.

@throws NameNotFoundException if component with given name doesn't exist.


public void addIntentFilterForReceiver(ComponentName componentName, IntentFilter filter)
      throws NameNotFoundException {
    addIntentFilterForComponent(componentName, filter, receiverFilters);
  }

public void addIntentFilterForReceiver ( ComponentName componentName , IntentFilter filter ) throws NameNotFoundException { addIntentFilterForComponent ( componentName , filter , receiverFilters ) ; }

Add intent filter for given receiver.

@throws NameNotFoundException if component with given name doesn't exist.


public void addIntentFilterForProvider(ComponentName componentName, IntentFilter filter)
      throws NameNotFoundException {
    addIntentFilterForComponent(componentName, filter, providerFilters);
  }

public void addIntentFilterForProvider ( ComponentName componentName , IntentFilter filter ) throws NameNotFoundException { addIntentFilterForComponent ( componentName , filter , providerFilters ) ; }

Add intent filter for given provider.

@throws NameNotFoundException if component with given name doesn't exist.


private static int findParent(int packed_locale, final String script) {
    if (hasRegion(packed_locale)) {
      for (Map.Entry<String, Map<Integer, Integer>> entry : SCRIPT_PARENTS.entrySet()) {
        if (script.equals(entry.getKey())) {
          Map<Integer, Integer> map = entry.getValue();
          Integer lookup_result = map.get(packed_locale);
          if (lookup_result != null) {
            return lookup_result;
          }
          break;
        }
      }
      return dropRegion(packed_locale);
    }
    return PACKED_ROOT;
  }

private static int findParent ( int packed_locale , final String script ) { if ( hasRegion ( packed_locale ) ) { for ( Map . Entry < String , Map < Integer , Integer > > entry : SCRIPT_PARENTS . entrySet ( ) ) { if ( script . equals ( entry . getKey ( ) ) ) { Map < Integer , Integer > map = entry . getValue ( ) ; Integer lookup_result = map . get ( packed_locale ) ; if ( lookup_result != null ) { return lookup_result ; } break ; } } return dropRegion ( packed_locale ) ; } return PACKED_ROOT ; }


static int findAncestors(int[] out, Ref<Long> stop_list_index,
      int packed_locale, final String script,
      final int[] stop_list, int stop_set_length) {
    int ancestor = packed_locale;
    int count = 0;
    do {
      if (out != null) {
        out[count] = ancestor;
      }
      count++;
      for (int i = 0; i < stop_set_length; i++) {
        if (stop_list[i] == ancestor) {
          stop_list_index.set((long) i);
          return count;
        }
      }
      ancestor = findParent(ancestor, script);
    } while (ancestor != PACKED_ROOT);
    stop_list_index.set((long) -1);
    return count;
  }

static int findAncestors ( int [ ] out , Ref < Long > stop_list_index , int packed_locale , final String script , final int [ ] stop_list , int stop_set_length ) { int ancestor = packed_locale ; int count = 0 ; do { if ( out != null ) { out [ count ] = ancestor ; } count ++ ; for ( int i = 0 ; i < stop_set_length ; i ++ ) { if ( stop_list [ i ] == ancestor ) { stop_list_index . set ( ( long ) i ) ; return count ; } } ancestor = findParent ( ancestor , script ) ; } while ( ancestor != PACKED_ROOT ) ; stop_list_index . set ( ( long ) - 1 ) ; return count ; }