com.android.internal.annotations.VisibleForTesting Java Examples

The following examples show how to use com.android.internal.annotations.VisibleForTesting. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LongitudinalReportingEncoder.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Get PRR result that with probability p is 1, probability 1-p is 0.
 */
@VisibleForTesting
public static boolean getLongTermRandomizedResult(double p, boolean secureEncoder,
        byte[] userSecret, String encoderId) {
    // Use Rappor to get PRR result. Rappor's P and Q are set to 0 and 1 so IRR will not be
    // effective.
    // As Rappor has rapporF/2 chance returns 0, rapporF/2 chance returns 1, and 1-rapporF
    // chance returns original input.
    // If p < 0.5, setting rapporF=2p and input=0 will make Rappor has p chance to return 1
    // P(output=1 | input=0) = rapporF/2 = 2p/2 = p.
    // If p >= 0.5, setting rapporF=2(1-p) and input=1 will make Rappor has p chance
    // to return 1.
    // P(output=1 | input=1) = rapporF/2 + (1 - rapporF) = 2(1-p)/2 + (1 - 2(1-p)) = p.
    final double effectiveF = p < 0.5f ? p * 2 : (1 - p) * 2;
    final boolean prrInput = p < 0.5f ? false : true;
    final RapporConfig prrConfig = new RapporConfig(encoderId, 1, effectiveF,
            0, 1, 1, 1);
    final RapporEncoder encoder = secureEncoder
            ? RapporEncoder.createEncoder(prrConfig, userSecret)
            : RapporEncoder.createInsecureEncoderForTest(prrConfig);
    return encoder.encodeBoolean(prrInput)[0] > 0;
}
 
Example #2
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Do not use directly; this returns uninstalled packages too.
 */
@Nullable
@VisibleForTesting
ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
        ComponentName activity, @UserIdInt int userId) {
    final long start = getStatStartTime();
    final long token = injectClearCallingIdentity();
    try {
        return mIPackageManager.getActivityInfo(activity,
                (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
    } catch (RemoteException e) {
        // Shouldn't happen.
        Slog.wtf(TAG, "RemoteException", e);
        return null;
    } finally {
        injectRestoreCallingIdentity(token);

        logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
    }
}
 
Example #3
Source File: IpSecConfig.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/** Copy constructor */
@VisibleForTesting
public IpSecConfig(IpSecConfig c) {
    mMode = c.mMode;
    mSourceAddress = c.mSourceAddress;
    mDestinationAddress = c.mDestinationAddress;
    mNetwork = c.mNetwork;
    mSpiResourceId = c.mSpiResourceId;
    mEncryption = c.mEncryption;
    mAuthentication = c.mAuthentication;
    mAuthenticatedEncryption = c.mAuthenticatedEncryption;
    mEncapType = c.mEncapType;
    mEncapSocketResourceId = c.mEncapSocketResourceId;
    mEncapRemotePort = c.mEncapRemotePort;
    mNattKeepaliveInterval = c.mNattKeepaliveInterval;
    mMarkValue = c.mMarkValue;
    mMarkMask = c.mMarkMask;
}
 
Example #4
Source File: NetworkWatchlistService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected boolean stopWatchlistLoggingImpl() {
    if (DEBUG) {
        Slog.i(TAG, "Stopping watchlist logging");
    }
    synchronized (mLoggingSwitchLock) {
        if (!mIsLoggingEnabled) {
            Slog.w(TAG, "Watchlist logging is not running");
            return true;
        }
        // stop the logging regardless of whether we fail to unregister listener
        mIsLoggingEnabled = false;

        try {
            return mIpConnectivityMetrics.removeNetdEventCallback(
                    INetdEventCallback.CALLBACK_CALLER_NETWORK_WATCHLIST);
        } catch (RemoteException re) {
            // Should not happen
            return false;
        }
    }
}
 
Example #5
Source File: NetworkStatsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
NetworkStatsService(Context context, INetworkManagementService networkManager,
        AlarmManager alarmManager, PowerManager.WakeLock wakeLock, Clock clock,
        TelephonyManager teleManager, NetworkStatsSettings settings,
        NetworkStatsObservers statsObservers, File systemDir, File baseDir) {
    mContext = checkNotNull(context, "missing Context");
    mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
    mAlarmManager = checkNotNull(alarmManager, "missing AlarmManager");
    mClock = checkNotNull(clock, "missing Clock");
    mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
    mTeleManager = checkNotNull(teleManager, "missing TelephonyManager");
    mWakeLock = checkNotNull(wakeLock, "missing WakeLock");
    mStatsObservers = checkNotNull(statsObservers, "missing NetworkStatsObservers");
    mSystemDir = checkNotNull(systemDir, "missing systemDir");
    mBaseDir = checkNotNull(baseDir, "missing baseDir");
    mUseBpfTrafficStats = new File("/sys/fs/bpf/traffic_uid_stats_map").exists();

    LocalServices.addService(NetworkStatsManagerInternal.class,
            new NetworkStatsManagerInternalImpl());
}
 
Example #6
Source File: PowerManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
PowerManagerService(Context context, BatterySaverPolicy batterySaverPolicy) {
    super(context);

    mContext = context;
    mHandlerThread = new ServiceThread(TAG,
            Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
    mConstants = new Constants(mHandler);
    mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
    mDisplaySuspendBlocker = null;
    mWakeLockSuspendBlocker = null;

    mBatterySavingStats = new BatterySavingStats(mLock);
    mBatterySaverPolicy = batterySaverPolicy;
    mBatterySaverController = new BatterySaverController(mLock, context,
            BackgroundThread.getHandler().getLooper(), batterySaverPolicy, mBatterySavingStats);
    mBatterySaverStateMachine = new BatterySaverStateMachine(
            mLock, mContext, mBatterySaverController);
}
 
Example #7
Source File: BrightnessTracker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/** Stop listening for events */
@VisibleForTesting
void stop() {
    if (DEBUG) {
        Slog.d(TAG, "Stop");
    }
    mBgHandler.removeMessages(MSG_BACKGROUND_START);
    stopSensorListener();
    mInjector.unregisterSensorListener(mContext, mSensorListener);
    mInjector.unregisterBrightnessModeObserver(mContext, mSettingsObserver);
    mInjector.unregisterReceiver(mContext, mBroadcastReceiver);
    mInjector.cancelIdleJob(mContext);

    synchronized (mDataCollectionLock) {
        mStarted = false;
    }
}
 
Example #8
Source File: LockTaskController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Translates from LockTask feature flags to StatusBarManager disable and disable2 flags.
 * @param lockTaskFlags Bitfield of flags as per
 *                      {@link DevicePolicyManager#setLockTaskFeatures(ComponentName, int)}
 * @return A {@link Pair} of {@link StatusBarManager#disable(int)} and
 *         {@link StatusBarManager#disable2(int)} flags
 */
@VisibleForTesting
Pair<Integer, Integer> getStatusBarDisableFlags(int lockTaskFlags) {
    // Everything is disabled by default
    int flags1 = StatusBarManager.DISABLE_MASK;
    int flags2 = StatusBarManager.DISABLE2_MASK;
    for (int i = STATUS_BAR_FLAG_MAP_LOCKED.size() - 1; i >= 0; i--) {
        Pair<Integer, Integer> statusBarFlags = STATUS_BAR_FLAG_MAP_LOCKED.valueAt(i);
        if ((STATUS_BAR_FLAG_MAP_LOCKED.keyAt(i) & lockTaskFlags) != 0) {
            flags1 &= ~statusBarFlags.first;
            flags2 &= ~statusBarFlags.second;
        }
    }
    // Some flags are not used for LockTask purposes, so we mask them
    flags1 &= STATUS_BAR_MASK_LOCKED;
    return new Pair<>(flags1, flags2);
}
 
Example #9
Source File: PowerManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
// lastRebootReasonProperty argument to permit testing
int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
    String line = SystemProperties.get(lastRebootReasonProperty);
    if (line == null) {
        return PowerManager.SHUTDOWN_REASON_UNKNOWN;
    }
    switch (line) {
        case REASON_SHUTDOWN:
            return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
        case REASON_REBOOT:
            return PowerManager.SHUTDOWN_REASON_REBOOT;
        case REASON_USERREQUESTED:
            return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
        case REASON_THERMAL_SHUTDOWN:
            return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
        case REASON_LOW_BATTERY:
            return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
        case REASON_BATTERY_THERMAL_STATE:
            return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
        default:
            return PowerManager.SHUTDOWN_REASON_UNKNOWN;
    }
}
 
Example #10
Source File: ZenModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected boolean evaluateZenMode(String reason, boolean setRingerMode) {
    if (DEBUG) Log.d(TAG, "evaluateZenMode");
    final int zenBefore = mZenMode;
    final int zen = computeZenMode();
    ZenLog.traceSetZenMode(zen, reason);
    mZenMode = zen;
    setZenModeSetting(mZenMode);
    updateRingerModeAffectedStreams();
    if (setRingerMode && zen != zenBefore) {
        applyZenToRingerMode();
    }
    applyRestrictions();
    if (zen != zenBefore) {
        mHandler.postDispatchOnZenModeChanged();
    }
    return true;
}
 
Example #11
Source File: TaskSnapshotSurface.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void drawBackgroundAndBars(Canvas c, Rect frame) {
    final int statusBarHeight = mSystemBarBackgroundPainter.getStatusBarColorViewHeight();
    final boolean fillHorizontally = c.getWidth() > frame.right;
    final boolean fillVertically = c.getHeight() > frame.bottom;
    if (fillHorizontally) {
        c.drawRect(frame.right, alpha(mStatusBarColor) == 0xFF ? statusBarHeight : 0,
                c.getWidth(), fillVertically
                        ? frame.bottom
                        : c.getHeight(),
                mBackgroundPaint);
    }
    if (fillVertically) {
        c.drawRect(0, frame.bottom, c.getWidth(), c.getHeight(), mBackgroundPaint);
    }
    mSystemBarBackgroundPainter.drawDecors(c, frame);
}
 
Example #12
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void validateAlgorithms(IpSecConfig config) throws IllegalArgumentException {
    IpSecAlgorithm auth = config.getAuthentication();
    IpSecAlgorithm crypt = config.getEncryption();
    IpSecAlgorithm aead = config.getAuthenticatedEncryption();

    // Validate the algorithm set
    Preconditions.checkArgument(
            aead != null || crypt != null || auth != null,
            "No Encryption or Authentication algorithms specified");
    Preconditions.checkArgument(
            auth == null || auth.isAuthentication(),
            "Unsupported algorithm for Authentication");
    Preconditions.checkArgument(
            crypt == null || crypt.isEncryption(), "Unsupported algorithm for Encryption");
    Preconditions.checkArgument(
            aead == null || aead.isAead(),
            "Unsupported algorithm for Authenticated Encryption");
    Preconditions.checkArgument(
            aead == null || (auth == null && crypt == null),
            "Authenticated Encryption is mutually exclusive with other Authentication "
                    + "or Encryption algorithms");
}
 
Example #13
Source File: DropBoxManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of managed drop box storage.  Normally there is one of these
 * run by the system, but others can be created for testing and other purposes.
 *
 * @param context to use for receiving free space & gservices intents
 * @param path to store drop box entries in
 */
@VisibleForTesting
public DropBoxManagerService(final Context context, File path, Looper looper) {
    super(context);
    mDropBoxDir = path;
    mContentResolver = getContext().getContentResolver();
    mHandler = new Handler(looper) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_SEND_BROADCAST) {
                getContext().sendBroadcastAsUser((Intent)msg.obj, UserHandle.SYSTEM,
                        android.Manifest.permission.READ_LOGS);
            }
        }
    };
}
 
Example #14
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
@GuardedBy("mAppRestrictionsLock")
static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
    FileOutputStream fos = null;
    try {
        fos = restrictionsFile.startWrite();
        final BufferedOutputStream bos = new BufferedOutputStream(fos);

        final XmlSerializer serializer = new FastXmlSerializer();
        serializer.setOutput(bos, StandardCharsets.UTF_8.name());
        serializer.startDocument(null, true);
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

        serializer.startTag(null, TAG_RESTRICTIONS);
        writeBundle(restrictions, serializer);
        serializer.endTag(null, TAG_RESTRICTIONS);

        serializer.endDocument();
        restrictionsFile.finishWrite(fos);
    } catch (Exception e) {
        restrictionsFile.failWrite(fos);
        Slog.e(LOG_TAG, "Error writing application restrictions list", e);
    }
}
 
Example #15
Source File: PrivacyUtils.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a map that stores appDigest, encoded_visitedWatchlist pairs.
 */
@VisibleForTesting
static Map<String, Boolean> createDpEncodedReportMap(boolean isSecure, byte[] userSecret,
        List<String> appDigestList, WatchlistReportDbHelper.AggregatedResult aggregatedResult) {
    if (DEBUG) Slog.i(TAG, "createDpEncodedReportMap start");
    final int appDigestListSize = appDigestList.size();
    final HashMap<String, Boolean> resultMap = new HashMap<>(appDigestListSize);
    for (int i = 0; i < appDigestListSize; i++) {
        final String appDigest = appDigestList.get(i);
        // Each app needs to have different PRR result, hence we use appDigest as encoder Id.
        final DifferentialPrivacyEncoder encoder = isSecure
                ? createSecureDPEncoder(userSecret, appDigest)
                : createInsecureDPEncoderForTest(appDigest);
        final boolean visitedWatchlist = aggregatedResult.appDigestList.contains(appDigest);
        if (DEBUG) Slog.i(TAG, appDigest + ": " + visitedWatchlist);
        // Get the least significant bit of first byte, and set result to True if it is 1
        boolean encodedVisitedWatchlist = ((int) encoder.encodeBoolean(visitedWatchlist)[0]
                & 0x1) == 0x1;
        resultMap.put(appDigest, encodedVisitedWatchlist);
    }
    return resultMap;
}
 
Example #16
Source File: MemoryStatUtil.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Parses relevant statistics out from the contents of a memory.stat file in memcg.
 */
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
@Nullable
static MemoryStat parseMemoryStatFromMemcg(String memoryStatContents) {
    if (memoryStatContents == null || memoryStatContents.isEmpty()) {
        return null;
    }

    final MemoryStat memoryStat = new MemoryStat();
    Matcher m;
    m = PGFAULT.matcher(memoryStatContents);
    memoryStat.pgfault = m.find() ? Long.valueOf(m.group(1)) : 0;
    m = PGMAJFAULT.matcher(memoryStatContents);
    memoryStat.pgmajfault = m.find() ? Long.valueOf(m.group(1)) : 0;
    m = RSS_IN_BYTES.matcher(memoryStatContents);
    memoryStat.rssInBytes = m.find() ? Long.valueOf(m.group(1)) : 0;
    m = CACHE_IN_BYTES.matcher(memoryStatContents);
    memoryStat.cacheInBytes = m.find() ? Long.valueOf(m.group(1)) : 0;
    m = SWAP_IN_BYTES.matcher(memoryStatContents);
    memoryStat.swapInBytes = m.find() ? Long.valueOf(m.group(1)) : 0;
    return memoryStat;
}
 
Example #17
Source File: TaskSnapshotSurface.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Calculates the snapshot frame in window coordinate space from crop.
 *
 * @param crop rect that is in snapshot coordinate space.
 */
@VisibleForTesting
Rect calculateSnapshotFrame(Rect crop) {
    final Rect frame = new Rect(crop);
    final float scale = mSnapshot.getScale();

    // Rescale the frame from snapshot to window coordinate space
    frame.scale(1 / scale);

    // By default, offset it to to top/left corner
    frame.offsetTo((int) (-crop.left / scale), (int) (-crop.top / scale));

    // However, we also need to make space for the navigation bar on the left side.
    final int colorViewLeftInset = getColorViewLeftInset(mStableInsets.left,
            mContentInsets.left);
    frame.offset(colorViewLeftInset, 0);
    return frame;
}
 
Example #18
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Analyzes the passed LinkedProperties to figure out whether it routes to most of the IP space.
 *
 * This returns true if the passed LinkedProperties contains routes to either most of the IPv4
 * space or to most of the IPv6 address space, where "most" is defined by the value of the
 * MOST_IPV{4,6}_ADDRESSES_COUNT constants : if more than this number of addresses are matched
 * by any of the routes, then it's decided that most of the space is routed.
 * @hide
 */
@VisibleForTesting
static boolean providesRoutesToMostDestinations(LinkProperties lp) {
    final List<RouteInfo> routes = lp.getAllRoutes();
    if (routes.size() > MAX_ROUTES_TO_EVALUATE) return true;
    final Comparator<IpPrefix> prefixLengthComparator = IpPrefix.lengthComparator();
    TreeSet<IpPrefix> ipv4Prefixes = new TreeSet<>(prefixLengthComparator);
    TreeSet<IpPrefix> ipv6Prefixes = new TreeSet<>(prefixLengthComparator);
    for (final RouteInfo route : routes) {
        IpPrefix destination = route.getDestination();
        if (destination.isIPv4()) {
            ipv4Prefixes.add(destination);
        } else {
            ipv6Prefixes.add(destination);
        }
    }
    if (NetworkUtils.routedIPv4AddressCount(ipv4Prefixes) > MOST_IPV4_ADDRESSES_COUNT) {
        return true;
    }
    return NetworkUtils.routedIPv6AddressCount(ipv6Prefixes)
            .compareTo(MOST_IPV6_ADDRESSES_COUNT) >= 0;
}
 
Example #19
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Removes a reference to this resource. If the resultant reference count is zero, the
 * underlying resources are freed, and references to all child resources are also dropped
 * recursively (resulting in them freeing their resources and children, etcetera)
 *
 * <p>This method also sets the reference count to an invalid value (-1) to signify that it
 * has been fully released. Any subsequent calls to this method will result in an
 * IllegalStateException being thrown due to resource already having been previously
 * released
 */
@VisibleForTesting
@GuardedBy("IpSecService.this")
public void releaseReference() throws RemoteException {
    mRefCount--;

    if (mRefCount > 0) {
        return;
    } else if (mRefCount < 0) {
        throw new IllegalStateException(
                "Invalid operation - resource has already been released.");
    }

    // Cleanup own resources
    mResource.freeUnderlyingResources();

    // Cleanup child resources as needed
    for (RefcountedResource<? extends IResource> child : mChildren) {
        child.releaseReference();
    }

    // Enforce that resource cleanup can only be called once
    // By decrementing the refcount (from 0 to -1), the next call will throw an
    // IllegalStateException - it has already been released fully.
    mRefCount--;
}
 
Example #20
Source File: ShortcutInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Look up resource name for a given resource ID.
 *
 * @return a simple resource name (e.g. "text_1") when {@code withType} is false, or with the
 * type (e.g. "string/text_1").
 *
 * @hide
 */
@VisibleForTesting
public static String lookUpResourceName(@NonNull Resources res, int resId, boolean withType,
        @NonNull String packageName) {
    if (resId == 0) {
        return null;
    }
    try {
        final String fullName = res.getResourceName(resId);

        if (ANDROID_PACKAGE_NAME.equals(getResourcePackageName(fullName))) {
            // If it's a framework resource, the value won't change, so just return the ID
            // value as a string.
            return String.valueOf(resId);
        }
        return withType ? getResourceTypeAndEntryName(fullName)
                : getResourceEntryName(fullName);
    } catch (NotFoundException e) {
        Log.e(TAG, "Resource name for ID=" + resId + " not found in package " + packageName
                + ". Resource IDs may change when the application is upgraded, and the system"
                + " may not be able to find the correct resource.");
        return null;
    }
}
 
Example #21
Source File: WorkSource.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** @hide */
@VisibleForTesting
public WorkChain(WorkChain other) {
    mSize = other.mSize;
    mUids = other.mUids.clone();
    mTags = other.mTags.clone();
}
 
Example #22
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
    synchronized (mLock) {
        final ShortcutUser user = mUsers.get(userId);
        if (user == null) return null;

        return user.getAllPackagesForTest().get(packageName);
    }
}
 
Example #23
Source File: NetworkStatsService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void setUidForeground(int uid, boolean uidForeground) {
    synchronized (mStatsLock) {
        final int set = uidForeground ? SET_FOREGROUND : SET_DEFAULT;
        final int oldSet = mActiveUidCounterSet.get(uid, SET_DEFAULT);
        if (oldSet != set) {
            mActiveUidCounterSet.put(uid, set);
            setKernelCounterSet(uid, set);
        }
    }
}
 
Example #24
Source File: FileUtils.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static long copyInternalUserspace(InputStream in, OutputStream out,
        ProgressListener listener, CancellationSignal signal) throws IOException {
    long progress = 0;
    long checkpoint = 0;
    byte[] buffer = new byte[8192];

    int t;
    while ((t = in.read(buffer)) != -1) {
        out.write(buffer, 0, t);

        progress += t;
        checkpoint += t;

        if (checkpoint >= COPY_CHECKPOINT_BYTES) {
            if (signal != null) {
                signal.throwIfCanceled();
            }
            if (listener != null) {
                listener.onProgress(progress);
            }
            checkpoint = 0;
        }
    }
    if (listener != null) {
        listener.onProgress(progress);
    }
    return progress;
}
 
Example #25
Source File: TransactionExecutorHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Pick a state that goes before provided post-execution state and would require the least
 * lifecycle transitions to get to.
 * It will also make sure to try avoiding a path with activity destruction and relaunch if
 * possible.
 * @param r An activity that we're trying to resolve the transition for.
 * @param postExecutionState Post execution state to compute for.
 * @return One of states that precede the provided post-execution state, or
 *         {@link ActivityLifecycleItem#UNDEFINED} if there is not path.
 */
@VisibleForTesting
public int getClosestPreExecutionState(ActivityClientRecord r,
        int postExecutionState) {
    switch (postExecutionState) {
        case UNDEFINED:
            return UNDEFINED;
        case ON_RESUME:
            return getClosestOfStates(r, ON_RESUME_PRE_EXCUTION_STATES);
        default:
            throw new UnsupportedOperationException("Pre-execution states for state: "
                    + postExecutionState + " is not supported.");
    }
}
 
Example #26
Source File: StorageManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** {@hide} */
@VisibleForTesting
public int getProxyFileDescriptorMountPointId() {
    synchronized (mFuseAppLoopLock) {
        return mFuseAppLoop != null ? mFuseAppLoop.getMountPointId() : -1;
    }
}
 
Example #27
Source File: TaskSnapshotSurface.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void drawStatusBarBackground(Canvas c, @Nullable Rect alreadyDrawnFrame,
        int statusBarHeight) {
    if (statusBarHeight > 0 && Color.alpha(mStatusBarColor) != 0
            && (alreadyDrawnFrame == null || c.getWidth() > alreadyDrawnFrame.right)) {
        final int rightInset = DecorView.getColorViewRightInset(mStableInsets.right,
                mContentInsets.right);
        final int left = alreadyDrawnFrame != null ? alreadyDrawnFrame.right : 0;
        c.drawRect(left, 0, c.getWidth() - rightInset, statusBarHeight, mStatusBarPaint);
    }
}
 
Example #28
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app,
        StorageManager storageManager, IPackageManager pm) {
    final VolumeInfo currentVol = getPackageCurrentVolume(app, storageManager);
    final List<VolumeInfo> vols = storageManager.getVolumes();
    final List<VolumeInfo> candidates = new ArrayList<>();
    for (VolumeInfo vol : vols) {
        if (Objects.equals(vol, currentVol)
                || isPackageCandidateVolume(mContext, app, vol, pm)) {
            candidates.add(vol);
        }
    }
    return candidates;
}
 
Example #29
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app,
        StorageManager storageManager, IPackageManager pm) {
    final VolumeInfo currentVol = getPackageCurrentVolume(app, storageManager);
    final List<VolumeInfo> vols = storageManager.getVolumes();
    final List<VolumeInfo> candidates = new ArrayList<>();
    for (VolumeInfo vol : vols) {
        if (Objects.equals(vol, currentVol)
                || isPackageCandidateVolume(mContext, app, vol, pm)) {
            candidates.add(vol);
        }
    }
    return candidates;
}
 
Example #30
Source File: ShortcutInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the type name + the entry name from a fully-donated resource name.
 * e.g. "com.android.app1:drawable/icon1" -> "drawable/icon1"
 * @hide
 */
@VisibleForTesting
public static String getResourceTypeAndEntryName(@NonNull String fullResourceName) {
    final int p1 = fullResourceName.indexOf(':');
    if (p1 < 0) {
        return null;
    }
    return fullResourceName.substring(p1 + 1);
}