libcore.io.IoUtils Java Examples

The following examples show how to use libcore.io.IoUtils. 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: FileInputStream.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException {
    guard.close();
    synchronized (this) {
        if (channel != null) {
            channel.close();
        }
        if (shouldClose) {
            IoUtils.close(fd);
        } else {
            // An owned fd has been invalidated by IoUtils.close, but
            // we need to explicitly stop using an unowned fd (http://b/4361076).
            fd = new FileDescriptor();
        }
    }
}
 
Example #2
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (isDirectory) {
        String path = new File(dir, name).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.

        String entryName = new File(dir, name).getPath();
        if (urlHandler.isEntryStored(entryName)) {
          return zip.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example #3
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (isDirectory) {
        String path = new File(dir, name).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    } else if (zipFile != null) {
        String entryName = new File(dir, name).getPath();
        if (isZipEntryExistsAndStored(zipFile, entryName)) {
          return zip.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example #4
Source File: BrightnessTracker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void readEvents() {
    synchronized (mEventsLock) {
        // Read might prune events so mark as dirty.
        mEventsDirty = true;
        mEvents.clear();
        final AtomicFile readFrom = mInjector.getFile(EVENTS_FILE);
        if (readFrom != null && readFrom.exists()) {
            FileInputStream input = null;
            try {
                input = readFrom.openRead();
                readEventsLocked(input);
            } catch (IOException e) {
                readFrom.delete();
                Slog.e(TAG, "Failed to read change mEvents.", e);
            } finally {
                IoUtils.closeQuietly(input);
            }
        }
    }
}
 
Example #5
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (isDirectory) {
        String path = new File(dir, name).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.

        String entryName = new File(dir, name).getPath();
        if (urlHandler.isEntryStored(entryName)) {
          return zip.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example #6
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (zipDir == null) {
        String entryPath = new File(path, name).getPath();
        if (IoUtils.canOpenReadOnly(entryPath)) {
            return entryPath;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.
        String entryName = zipDir + '/' + name;
        if (urlHandler.isEntryStored(entryName)) {
          return path.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example #7
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (zipDir == null) {
        String entryPath = new File(path, name).getPath();
        if (IoUtils.canOpenReadOnly(entryPath)) {
            return entryPath;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.
        String entryName = zipDir + '/' + name;
        if (urlHandler.isEntryStored(entryName)) {
          return path.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example #8
Source File: File.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new, empty file on the file system according to the path
 * information stored in this file. This method returns true if it creates
 * a file, false if the file already existed. Note that it returns false
 * even if the file is not a file (because it's a directory, say).
 *
 * <p>This method is not generally useful. For creating temporary files,
 * use {@link #createTempFile} instead. For reading/writing files, use {@link FileInputStream},
 * {@link FileOutputStream}, or {@link RandomAccessFile}, all of which can create files.
 *
 * <p>Note that this method does <i>not</i> throw {@code IOException} if the file
 * already exists, even if it's not a regular file. Callers should always check the
 * return value, and may additionally want to call {@link #isFile}.
 *
 * @return true if the file has been created, false if it
 *         already exists.
 * @throws IOException if it's not possible to create the file.
 */
public boolean createNewFile() throws IOException {
    if (0 == path.length()) {
        throw new IOException("No such file or directory");
    }
    if (isDirectory()) {  // true for paths like "dir/..", which can't be files.
        throw new IOException("Cannot create: " + path);
    }
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        fd = Libcore.os.open(path, O_RDWR | O_CREAT | O_EXCL, 0600);
        return true;
    } catch (ErrnoException errnoException) {
        if (errnoException.errno == EEXIST) {
            // The file already exists.
            return false;
        }
        throw errnoException.rethrowAsIOException();
    } finally {
        IoUtils.close(fd); // TODO: should we suppress IOExceptions thrown here?
    }
}
 
Example #9
Source File: BrightnessTracker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void readAmbientBrightnessStats() {
    mAmbientBrightnessStatsTracker = new AmbientBrightnessStatsTracker(mUserManager, null);
    final AtomicFile readFrom = mInjector.getFile(AMBIENT_BRIGHTNESS_STATS_FILE);
    if (readFrom != null && readFrom.exists()) {
        FileInputStream input = null;
        try {
            input = readFrom.openRead();
            mAmbientBrightnessStatsTracker.readStats(input);
        } catch (IOException e) {
            readFrom.delete();
            Slog.e(TAG, "Failed to read ambient brightness stats.", e);
        } finally {
            IoUtils.closeQuietly(input);
        }
    }
}
 
Example #10
Source File: ArtManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void postSuccess(String packageName, ParcelFileDescriptor fd,
        ISnapshotRuntimeProfileCallback callback) {
    if (DEBUG) {
        Slog.d(TAG, "Successfully snapshot profile for " + packageName);
    }
    mHandler.post(() -> {
        try {
            // Double check that the descriptor is still valid.
            // We've seen production issues (b/76028139) where this can turn invalid (there are
            // suspicions around the finalizer behaviour).
            if (fd.getFileDescriptor().valid()) {
                callback.onSuccess(fd);
            } else {
                Slog.wtf(TAG, "The snapshot FD became invalid before posting the result for "
                        + packageName);
                callback.onError(ArtManager.SNAPSHOT_FAILED_INTERNAL_ERROR);
            }
        } catch (Exception e) {
            Slog.w(TAG,
                    "Failed to call onSuccess after profile snapshot for " + packageName, e);
        } finally {
            IoUtils.closeQuietly(fd);
        }
    });
}
 
Example #11
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private UserData readUserLP(int id) {
    FileInputStream fis = null;
    try {
        AtomicFile userFile =
                new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
        fis = userFile.openRead();
        return readUserLP(id, fis);
    } catch (IOException ioe) {
        Slog.e(LOG_TAG, "Error reading user list");
    } catch (XmlPullParserException pe) {
        Slog.e(LOG_TAG, "Error reading user list");
    } finally {
        IoUtils.closeQuietly(fis);
    }
    return null;
}
 
Example #12
Source File: PackageInstallerSession.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private static void extractNativeLibraries(File packageDir, String abiOverride, boolean inherit)
        throws PackageManagerException {
    final File libDir = new File(packageDir, NativeLibraryHelper.LIB_DIR_NAME);
    if (!inherit) {
        // Start from a clean slate
        NativeLibraryHelper.removeNativeBinariesFromDirLI(libDir, true);
    }

    NativeLibraryHelper.Handle handle = null;
    try {
        handle = NativeLibraryHelper.Handle.create(packageDir);
        final int res = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libDir,
                abiOverride);
        if (res != PackageManager.INSTALL_SUCCEEDED) {
            throw new PackageManagerException(res,
                    "Failed to extract native libraries, res=" + res);
        }
    } catch (IOException e) {
        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
                "Failed to extract native libraries", e);
    } finally {
        IoUtils.closeQuietly(handle);
    }
}
 
Example #13
Source File: PackageManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private int doRemoveSplit(int sessionId, String splitName, boolean logSuccess)
        throws RemoteException {
    final PrintWriter pw = getOutPrintWriter();
    PackageInstaller.Session session = null;
    try {
        session = new PackageInstaller.Session(
                mInterface.getPackageInstaller().openSession(sessionId));
        session.removeSplit(splitName);

        if (logSuccess) {
            pw.println("Success");
        }
        return 0;
    } catch (IOException e) {
        pw.println("Error: failed to remove split; " + e.getMessage());
        return 1;
    } finally {
        IoUtils.closeQuietly(session);
    }
}
 
Example #14
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (zipDir == null) {
        String entryPath = new File(path, name).getPath();
        if (IoUtils.canOpenReadOnly(entryPath)) {
            return entryPath;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.
        String entryName = zipDir + '/' + name;
        if (urlHandler.isEntryStored(entryName)) {
          return path.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example #15
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
        throws IOException {
    assertTrue(this.channel2.isBlocking());

    new Thread() {
        public void run() {
            try {
                Thread.sleep(TIME_UNIT);
            } catch (InterruptedException ie) {
                fail();
            }
            IoUtils.closeQuietly(channel2);
        }
    }.start();

    try {
        this.channel2.read(targetBuf);
        fail("Should throw AsynchronousCloseException");
    } catch (AsynchronousCloseException e) {
        // OK.
    }
}
 
Example #16
Source File: Network.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private Socket connectToHost(String host, int port, SocketAddress localAddress)
        throws IOException {
    // Lookup addresses only on this Network.
    InetAddress[] hostAddresses = getAllByName(host);
    // Try all addresses.
    for (int i = 0; i < hostAddresses.length; i++) {
        try {
            Socket socket = createSocket();
            boolean failed = true;
            try {
                if (localAddress != null) socket.bind(localAddress);
                socket.connect(new InetSocketAddress(hostAddresses[i], port));
                failed = false;
                return socket;
            } finally {
                if (failed) IoUtils.closeQuietly(socket);
            }
        } catch (IOException e) {
            if (i == (hostAddresses.length - 1)) throw e;
        }
    }
    throw new UnknownHostException(host);
}
 
Example #17
Source File: FileInputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        FileOutputStream fos = new FileOutputStream(mOutFd);
        try {
            byte[] buffer = new byte[TOTAL_SIZE];
            for (int i = 0; i < buffer.length; ++i) {
                buffer[i] = (byte) i;
            }
            fos.write(buffer);
        } finally {
            IoUtils.closeQuietly(fos);
            IoUtils.close(mOutFd);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: DocumentsProvider.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Return a list of streamable MIME types matching the filter, which can be passed to
 * {@link #openTypedDocument(String, String, Bundle, CancellationSignal)}.
 *
 * <p>The default implementation returns a MIME type provided by
 * {@link #queryDocument(String, String[])} as long as it matches the filter and the document
 * does not have the {@link Document#FLAG_VIRTUAL_DOCUMENT} flag set.
 *
 * <p>Virtual documents must have at least one streamable format.
 *
 * @see #getStreamTypes(Uri, String)
 * @see #openTypedDocument(String, String, Bundle, CancellationSignal)
 */
public String[] getDocumentStreamTypes(String documentId, String mimeTypeFilter) {
    Cursor cursor = null;
    try {
        cursor = queryDocument(documentId, null);
        if (cursor.moveToFirst()) {
            final String mimeType =
                cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE));
            final long flags =
                cursor.getLong(cursor.getColumnIndexOrThrow(Document.COLUMN_FLAGS));
            if ((flags & Document.FLAG_VIRTUAL_DOCUMENT) == 0 && mimeType != null &&
                    mimeTypeMatches(mimeTypeFilter, mimeType)) {
                return new String[] { mimeType };
            }
        }
    } catch (FileNotFoundException e) {
        return null;
    } finally {
        IoUtils.closeQuietly(cursor);
    }

    // No streamable MIME types.
    return null;
}
 
Example #19
Source File: UiAutomationConnection.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        final byte[] buffer = new byte[8192];
        int readByteCount;
        while (true) {
            readByteCount = readFrom.read(buffer);
            if (readByteCount < 0) {
                break;
            }
            writeTo.write(buffer, 0, readByteCount);
            writeTo.flush();
        }
    } catch (IOException ioe) {
        throw new RuntimeException("Error while reading/writing ", ioe);
    } finally {
        IoUtils.closeQuietly(readFrom);
        IoUtils.closeQuietly(writeTo);
    }
}
 
Example #20
Source File: FileUtils.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final FileDescriptor fd = getInternalFD();
    try {
        int i = 0;
        while (i < data.length) {
            if (sink) {
                i += Os.read(fd, data, i, data.length - i);
            } else {
                i += Os.write(fd, data, i, data.length - i);
            }
        }
    } catch (IOException | ErrnoException e) {
        // Ignored
    } finally {
        if (sink) {
            SystemClock.sleep(TimeUnit.SECONDS.toMillis(1));
        }
        IoUtils.closeQuietly(fd);
    }
}
 
Example #21
Source File: AppFuseBridge.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public ParcelFileDescriptor addBridge(MountScope mountScope)
        throws FuseUnavailableMountException, NativeDaemonConnectorException {
    try {
        synchronized (this) {
            Preconditions.checkArgument(mScopes.indexOfKey(mountScope.mountId) < 0);
            if (mNativeLoop == 0) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final int fd = native_add_bridge(
                    mNativeLoop, mountScope.mountId, mountScope.open().detachFd());
            if (fd == -1) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final ParcelFileDescriptor result = ParcelFileDescriptor.adoptFd(fd);
            mScopes.put(mountScope.mountId, mountScope);
            mountScope = null;
            return result;
        }
    } finally {
        IoUtils.closeQuietly(mountScope);
    }
}
 
Example #22
Source File: FileOutputStream.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException {
    guard.close();
    synchronized (this) {
        if (channel != null) {
            channel.close();
        }
        if (shouldClose) {
            IoUtils.close(fd);
        } else {
            // An owned fd has been invalidated by IoUtils.close, but
            // we need to explicitly stop using an unowned fd (http://b/4361076).
            fd = new FileDescriptor();
        }
    }
}
 
Example #23
Source File: NetworkStatsRecorder.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Recover from {@link FileRotator} failure by dumping state to
 * {@link DropBoxManager} and deleting contents.
 */
private void recoverFromWtf() {
    if (DUMP_BEFORE_DELETE) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            mRotator.dumpAll(os);
        } catch (IOException e) {
            // ignore partial contents
            os.reset();
        } finally {
            IoUtils.closeQuietly(os);
        }
        mDropBox.addData(TAG_NETSTATS_DUMP, os.toByteArray(), 0);
    }

    mRotator.deleteAll();
}
 
Example #24
Source File: InstantAppRegistry.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public byte[] getInstantAppCookieLPw(@NonNull String packageName,
        @UserIdInt int userId) {
    // Only installed packages can get their own cookie
    PackageParser.Package pkg = mService.mPackages.get(packageName);
    if (pkg == null) {
        return null;
    }

    byte[] pendingCookie = mCookiePersistence.getPendingPersistCookieLPr(pkg, userId);
    if (pendingCookie != null) {
        return pendingCookie;
    }
    File cookieFile = peekInstantCookieFile(packageName, userId);
    if (cookieFile != null && cookieFile.exists()) {
        try {
            return IoUtils.readFileAsByteArray(cookieFile.toString());
        } catch (IOException e) {
            Slog.w(LOG_TAG, "Error reading cookie file: " + cookieFile);
        }
    }
    return null;
}
 
Example #25
Source File: WallpaperManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Version of {@link #setStream(InputStream, Rect, boolean)} that allows the caller
 * to specify which of the supported wallpaper categories to set.
 *
 * @param bitmapData A stream containing the raw data to install as a wallpaper.  This
 *     data can be in any format handled by {@link BitmapRegionDecoder}.
 * @param visibleCropHint The rectangular subregion of the streamed image that should be
 *     displayed as wallpaper.  Passing {@code null} for this parameter means that
 *     the full image should be displayed if possible given the image's and device's
 *     aspect ratios, etc.
 * @param allowBackup {@code true} if the OS is permitted to back up this wallpaper
 *     image for restore to a future device; {@code false} otherwise.
 * @param which Flags indicating which wallpaper(s) to configure with the new imagery.
 * @return An integer ID assigned to the newly active wallpaper; or zero on failure.
 *
 * @see #getWallpaperId(int)
 * @see #FLAG_LOCK
 * @see #FLAG_SYSTEM
 *
 * @throws IOException
 */
@RequiresPermission(android.Manifest.permission.SET_WALLPAPER)
public int setStream(InputStream bitmapData, Rect visibleCropHint,
        boolean allowBackup, @SetWallpaperFlags int which)
                throws IOException {
    validateRect(visibleCropHint);
    if (sGlobals.mService == null) {
        Log.w(TAG, "WallpaperService not running");
        throw new RuntimeException(new DeadSystemException());
    }
    final Bundle result = new Bundle();
    final WallpaperSetCompletion completion = new WallpaperSetCompletion();
    try {
        ParcelFileDescriptor fd = sGlobals.mService.setWallpaper(null,
                mContext.getOpPackageName(), visibleCropHint, allowBackup,
                result, which, completion, mContext.getUserId());
        if (fd != null) {
            FileOutputStream fos = null;
            try {
                fos = new ParcelFileDescriptor.AutoCloseOutputStream(fd);
                copyStreamToWallpaperFile(bitmapData, fos);
                fos.close();
                completion.waitForCompletion();
            } finally {
                IoUtils.closeQuietly(fos);
            }
        }
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }

    return result.getInt(EXTRA_NEW_WALLPAPER_ID, 0);
}
 
Example #26
Source File: UiAutomation.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a shell command. This method returns two file descriptors,
 * one that points to the standard output stream (element at index 0), and one that points
 * to the standard input stream (element at index 1). The command execution is similar
 * to running "adb shell <command>" from a host connected to the device.
 * <p>
 * <strong>Note:</strong> It is your responsibility to close the returned file
 * descriptors once you are done reading/writing.
 * </p>
 *
 * @param command The command to execute.
 * @return File descriptors (out, in) to the standard output/input streams.
 *
 * @hide
 */
@TestApi
public ParcelFileDescriptor[] executeShellCommandRw(String command) {
    synchronized (mLock) {
        throwIfNotConnectedLocked();
    }
    warnIfBetterCommand(command);

    ParcelFileDescriptor source_read = null;
    ParcelFileDescriptor sink_read = null;

    ParcelFileDescriptor source_write = null;
    ParcelFileDescriptor sink_write = null;

    try {
        ParcelFileDescriptor[] pipe_read = ParcelFileDescriptor.createPipe();
        source_read = pipe_read[0];
        sink_read = pipe_read[1];

        ParcelFileDescriptor[] pipe_write = ParcelFileDescriptor.createPipe();
        source_write = pipe_write[0];
        sink_write = pipe_write[1];

        // Calling out without a lock held.
        mUiAutomationConnection.executeShellCommand(command, sink_read, source_write);
    } catch (IOException ioe) {
        Log.e(LOG_TAG, "Error executing shell command!", ioe);
    } catch (RemoteException re) {
        Log.e(LOG_TAG, "Error executing shell command!", re);
    } finally {
        IoUtils.closeQuietly(sink_read);
        IoUtils.closeQuietly(source_write);
    }

    ParcelFileDescriptor[] result = new ParcelFileDescriptor[2];
    result[0] = source_read;
    result[1] = sink_write;
    return result;
}
 
Example #27
Source File: RegisteredServicesCache.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@GuardedBy("mServicesLock")
private UserServices<V> findOrCreateUserLocked(int userId, boolean loadFromFileIfNew) {
    UserServices<V> services = mUserServices.get(userId);
    if (services == null) {
        services = new UserServices<V>();
        mUserServices.put(userId, services);
        if (loadFromFileIfNew && mSerializerAndParser != null) {
            // Check if user exists and try loading data from file
            // clear existing data if there was an error during migration
            UserInfo user = getUser(userId);
            if (user != null) {
                AtomicFile file = createFileForUser(user.id);
                if (file.getBaseFile().exists()) {
                    if (DEBUG) {
                        Slog.i(TAG, String.format("Loading u%s data from %s", user.id, file));
                    }
                    InputStream is = null;
                    try {
                        is = file.openRead();
                        readPersistentServicesLocked(is);
                    } catch (Exception e) {
                        Log.w(TAG, "Error reading persistent services for user " + user.id, e);
                    } finally {
                        IoUtils.closeQuietly(is);
                    }
                }
            }
        }
    }
    return services;
}
 
Example #28
Source File: ActivityThread.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private void handleDumpActivity(DumpComponentInfo info) {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        ActivityClientRecord r = mActivities.get(info.token);
        if (r != null && r.activity != null) {
            PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
            r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
            pw.flush();
        }
    } finally {
        IoUtils.closeQuietly(info.fd);
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example #29
Source File: UiAutomation.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a shell command. This method returns a file descriptor that points
 * to the standard output stream. The command execution is similar to running
 * "adb shell <command>" from a host connected to the device.
 * <p>
 * <strong>Note:</strong> It is your responsibility to close the returned file
 * descriptor once you are done reading.
 * </p>
 *
 * @param command The command to execute.
 * @return A file descriptor to the standard output stream.
 */
public ParcelFileDescriptor executeShellCommand(String command) {
    synchronized (mLock) {
        throwIfNotConnectedLocked();
    }
    warnIfBetterCommand(command);

    ParcelFileDescriptor source = null;
    ParcelFileDescriptor sink = null;

    try {
        ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
        source = pipe[0];
        sink = pipe[1];

        // Calling out without a lock held.
        mUiAutomationConnection.executeShellCommand(command, sink, null);
    } catch (IOException ioe) {
        Log.e(LOG_TAG, "Error executing shell command!", ioe);
    } catch (RemoteException re) {
        Log.e(LOG_TAG, "Error executing shell command!", re);
    } finally {
        IoUtils.closeQuietly(sink);
    }

    return source;
}
 
Example #30
Source File: FileBridge.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    try {
        writeCommandAndBlock(CMD_CLOSE, "close()");
    } finally {
        IoBridge.closeAndSignalBlockedThreads(mClient);
        IoUtils.closeQuietly(mClientPfd);
    }
}