Search in sources :

Example 76 with ParcelFileDescriptor

use of android.os.ParcelFileDescriptor in project remusic by aa112901.

the class ImageUtils method getArtworkQuick.

// Get album art for specified album. This method will not try to
// fall back to getting artwork directly from the file, nor will
// it attempt to repair the database.
public static Bitmap getArtworkQuick(Context context, long album_id, int w, int h) {
    // NOTE: There is in fact a 1 pixel border on the right side in the
    // ImageView
    // used to display this drawable. Take it into account now, so we don't
    // have to
    // scale later.
    w -= 1;
    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
    if (uri != null) {
        ParcelFileDescriptor fd = null;
        try {
            fd = res.openFileDescriptor(uri, "r");
            if (fd == null) {
                return null;
            }
            int sampleSize = 1;
            // Compute the closest power-of-two scale factor
            // and pass that to sBitmapOptionsCache.inSampleSize, which will
            // result in faster decoding and better quality
            sBitmapOptionsCache.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);
            int nextWidth = sBitmapOptionsCache.outWidth >> 1;
            int nextHeight = sBitmapOptionsCache.outHeight >> 1;
            while (nextWidth > w && nextHeight > h) {
                sampleSize <<= 1;
                nextWidth >>= 1;
                nextHeight >>= 1;
            }
            sBitmapOptionsCache.inSampleSize = sampleSize;
            sBitmapOptionsCache.inJustDecodeBounds = false;
            Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);
            if (b != null) {
                // finally rescale to exactly the size we need
                if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
                    Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
                    // bitmap
                    if (tmp != b)
                        b.recycle();
                    b = tmp;
                }
            }
            return b;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fd != null)
                    fd.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}
Also used : Bitmap(android.graphics.Bitmap) ParcelFileDescriptor(android.os.ParcelFileDescriptor) IOException(java.io.IOException) Uri(android.net.Uri) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ContentResolver(android.content.ContentResolver)

Example 77 with ParcelFileDescriptor

use of android.os.ParcelFileDescriptor in project android_frameworks_base by ParanoidAndroid.

the class ActivityManagerService method attachApplicationLocked.

private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
    // Find the application record that is being attached...  either via
    // the pid if we are running in multiple processes, or just pull the
    // next app record if we are emulating process with anonymous threads.
    ProcessRecord app;
    if (pid != MY_PID && pid >= 0) {
        synchronized (mPidsSelfLocked) {
            app = mPidsSelfLocked.get(pid);
        }
    } else {
        app = null;
    }
    if (app == null) {
        Slog.w(TAG, "No pending application record for pid " + pid + " (IApplicationThread " + thread + "); dropping process");
        EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
        if (pid > 0 && pid != MY_PID) {
            Process.killProcessQuiet(pid);
        } else {
            try {
                thread.scheduleExit();
            } catch (Exception e) {
            // Ignore exceptions.
            }
        }
        return false;
    }
    // process, clean it up now.
    if (app.thread != null) {
        handleAppDiedLocked(app, true, true);
    }
    if (localLOGV)
        Slog.v(TAG, "Binding process pid " + pid + " to record " + app);
    String processName = app.processName;
    try {
        AppDeathRecipient adr = new AppDeathRecipient(app, pid, thread);
        thread.asBinder().linkToDeath(adr, 0);
        app.deathRecipient = adr;
    } catch (RemoteException e) {
        app.resetPackageList();
        startProcessLocked(app, "link fail", processName);
        return false;
    }
    EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
    app.thread = thread;
    app.curAdj = app.setAdj = -100;
    app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
    app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
    app.forcingToForeground = null;
    app.foregroundServices = false;
    app.hasShownUi = false;
    app.debugging = false;
    mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
    boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
    List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
    if (!normalMode) {
        Slog.i(TAG, "Launching preboot mode app: " + app);
    }
    if (localLOGV)
        Slog.v(TAG, "New app record " + app + " thread=" + thread.asBinder() + " pid=" + pid);
    try {
        int testMode = IApplicationThread.DEBUG_OFF;
        if (mDebugApp != null && mDebugApp.equals(processName)) {
            testMode = mWaitForDebugger ? IApplicationThread.DEBUG_WAIT : IApplicationThread.DEBUG_ON;
            app.debugging = true;
            if (mDebugTransient) {
                mDebugApp = mOrigDebugApp;
                mWaitForDebugger = mOrigWaitForDebugger;
            }
        }
        String profileFile = app.instrumentationProfileFile;
        ParcelFileDescriptor profileFd = null;
        boolean profileAutoStop = false;
        if (mProfileApp != null && mProfileApp.equals(processName)) {
            mProfileProc = app;
            profileFile = mProfileFile;
            profileFd = mProfileFd;
            profileAutoStop = mAutoStopProfiler;
        }
        boolean enableOpenGlTrace = false;
        if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
            enableOpenGlTrace = true;
            mOpenGlTraceApp = null;
        }
        // If the app is being launched for restore or full backup, set it up specially
        boolean isRestrictedBackupMode = false;
        if (mBackupTarget != null && mBackupAppName.equals(processName)) {
            isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE) || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
        }
        ensurePackageDexOpt(app.instrumentationInfo != null ? app.instrumentationInfo.packageName : app.info.packageName);
        if (app.instrumentationClass != null) {
            ensurePackageDexOpt(app.instrumentationClass.getPackageName());
        }
        if (DEBUG_CONFIGURATION)
            Slog.v(TAG, "Binding proc " + processName + " with config " + mConfiguration);
        ApplicationInfo appInfo = app.instrumentationInfo != null ? app.instrumentationInfo : app.info;
        app.compat = compatibilityInfoForPackageLocked(appInfo);
        if (profileFd != null) {
            profileFd = profileFd.dup();
        }
        thread.bindApplication(processName, appInfo, providers, app.instrumentationClass, profileFile, profileFd, profileAutoStop, app.instrumentationArguments, app.instrumentationWatcher, app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(mConfiguration), app.compat, getCommonServicesLocked(), mCoreSettingsObserver.getCoreSettingsLocked());
        updateLruProcessLocked(app, false);
        app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
    } catch (Exception e) {
        // todo: Yikes!  What should we do?  For now we will try to
        // start another process, but that could easily get us in
        // an infinite loop of restarting processes...
        Slog.w(TAG, "Exception thrown during bind!", e);
        app.resetPackageList();
        app.unlinkDeathRecipient();
        startProcessLocked(app, "bind fail", processName);
        return false;
    }
    // Remove this record from the list of starting applications.
    mPersistentStartingProcesses.remove(app);
    if (DEBUG_PROCESSES && mProcessesOnHold.contains(app))
        Slog.v(TAG, "Attach application locked removing on hold: " + app);
    mProcessesOnHold.remove(app);
    boolean badApp = false;
    boolean didSomething = false;
    // See if the top visible activity is waiting to run in this process...
    ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
    if (hr != null && normalMode) {
        if (hr.app == null && app.uid == hr.info.applicationInfo.uid && processName.equals(hr.processName)) {
            try {
                if (mHeadless) {
                    Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
                } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.w(TAG, "Exception in new application when starting activity " + hr.intent.getComponent().flattenToShortString(), e);
                badApp = true;
            }
        } else {
            mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
        }
    }
    // Find any services that should be running in this process...
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName);
        } catch (Exception e) {
            badApp = true;
        }
    }
    // Check if a next-broadcast receiver is in this process...
    if (!badApp && isPendingBroadcastProcessLocked(pid)) {
        try {
            didSomething = sendPendingBroadcastsLocked(app);
        } catch (Exception e) {
            // If the app died trying to launch the receiver we declare it 'bad'
            badApp = true;
        }
    }
    // Check whether the next backup agent is in this process...
    if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
        if (DEBUG_BACKUP)
            Slog.v(TAG, "New app is backup target, launching agent for " + app);
        ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
        try {
            thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, compatibilityInfoForPackageLocked(mBackupTarget.appInfo), mBackupTarget.backupMode);
        } catch (Exception e) {
            Slog.w(TAG, "Exception scheduling backup agent creation: ");
            e.printStackTrace();
        }
    }
    if (badApp) {
        // todo: Also need to kill application to deal with all
        // kinds of exceptions.
        handleAppDiedLocked(app, false, true);
        return false;
    }
    if (!didSomething) {
        updateOomAdjLocked();
    }
    return true;
}
Also used : Configuration(android.content.res.Configuration) ParcelFileDescriptor(android.os.ParcelFileDescriptor) ApplicationInfo(android.content.pm.ApplicationInfo) ArrayList(java.util.ArrayList) RemoteCallbackList(android.os.RemoteCallbackList) List(java.util.List) RemoteException(android.os.RemoteException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ActivityNotFoundException(android.content.ActivityNotFoundException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException)

Example 78 with ParcelFileDescriptor

use of android.os.ParcelFileDescriptor in project android_frameworks_base by ParanoidAndroid.

the class WallpaperManagerService method updateWallpaperBitmapLocked.

ParcelFileDescriptor updateWallpaperBitmapLocked(String name, WallpaperData wallpaper) {
    if (name == null)
        name = "";
    try {
        File dir = getWallpaperDir(wallpaper.userId);
        if (!dir.exists()) {
            dir.mkdir();
            FileUtils.setPermissions(dir.getPath(), FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IXOTH, -1, -1);
        }
        File file = new File(dir, WALLPAPER);
        ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, MODE_CREATE | MODE_READ_WRITE);
        if (!SELinux.restorecon(file)) {
            return null;
        }
        wallpaper.name = name;
        return fd;
    } catch (FileNotFoundException e) {
        Slog.w(TAG, "Error setting wallpaper", e);
    }
    return null;
}
Also used : ParcelFileDescriptor(android.os.ParcelFileDescriptor) FileNotFoundException(java.io.FileNotFoundException) File(java.io.File) JournaledFile(com.android.internal.util.JournaledFile)

Example 79 with ParcelFileDescriptor

use of android.os.ParcelFileDescriptor in project android_frameworks_base by ParanoidAndroid.

the class ActivityManagerService method openContentUri.

public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
    enforceNotIsolatedCaller("openContentUri");
    final int userId = UserHandle.getCallingUserId();
    String name = uri.getAuthority();
    ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
    ParcelFileDescriptor pfd = null;
    if (cph != null) {
        // We record the binder invoker's uid in thread-local storage before
        // going to the content provider to open the file.  Later, in the code
        // that handles all permissions checks, we look for this uid and use
        // that rather than the Activity Manager's own uid.  The effect is that
        // we do the check against the caller's permissions even though it looks
        // to the content provider like the Activity Manager itself is making
        // the request.
        sCallerIdentity.set(new Identity(Binder.getCallingPid(), Binder.getCallingUid()));
        try {
            pfd = cph.provider.openFile(null, uri, "r");
        } catch (FileNotFoundException e) {
        // do nothing; pfd will be returned null
        } finally {
            // Ensure that whatever happens, we clean up the identity state
            sCallerIdentity.remove();
        }
        // We've got the fd now, so we're done with the provider.
        removeContentProviderExternalUnchecked(name, null, userId);
    } else {
        Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
    }
    return pfd;
}
Also used : ParcelFileDescriptor(android.os.ParcelFileDescriptor) FileNotFoundException(java.io.FileNotFoundException)

Example 80 with ParcelFileDescriptor

use of android.os.ParcelFileDescriptor in project android_frameworks_base by ParanoidAndroid.

the class Vpn method establish.

/**
     * Establish a VPN network and return the file descriptor of the VPN
     * interface. This methods returns {@code null} if the application is
     * revoked or not prepared.
     *
     * @param config The parameters to configure the network.
     * @return The file descriptor of the VPN interface.
     */
public synchronized ParcelFileDescriptor establish(VpnConfig config) {
    // Check if the caller is already prepared.
    PackageManager pm = mContext.getPackageManager();
    ApplicationInfo app = null;
    try {
        app = pm.getApplicationInfo(mPackage, 0);
    } catch (Exception e) {
        return null;
    }
    if (Binder.getCallingUid() != app.uid) {
        return null;
    }
    // Check if the service is properly declared.
    Intent intent = new Intent(VpnConfig.SERVICE_INTERFACE);
    intent.setClassName(mPackage, config.user);
    ResolveInfo info = pm.resolveService(intent, 0);
    if (info == null) {
        throw new SecurityException("Cannot find " + config.user);
    }
    if (!BIND_VPN_SERVICE.equals(info.serviceInfo.permission)) {
        throw new SecurityException(config.user + " does not require " + BIND_VPN_SERVICE);
    }
    // Load the label.
    String label = app.loadLabel(pm).toString();
    // Load the icon and convert it into a bitmap.
    Drawable icon = app.loadIcon(pm);
    Bitmap bitmap = null;
    if (icon.getIntrinsicWidth() > 0 && icon.getIntrinsicHeight() > 0) {
        int width = mContext.getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
        int height = mContext.getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
        icon.setBounds(0, 0, width, height);
        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);
        icon.draw(c);
        c.setBitmap(null);
    }
    // Configure the interface. Abort if any of these steps fails.
    ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
    try {
        updateState(DetailedState.CONNECTING, "establish");
        String interfaze = jniGetName(tun.getFd());
        if (jniSetAddresses(interfaze, config.addresses) < 1) {
            throw new IllegalArgumentException("At least one address must be specified");
        }
        if (config.routes != null) {
            jniSetRoutes(interfaze, config.routes);
        }
        Connection connection = new Connection();
        if (!mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
            throw new IllegalStateException("Cannot bind " + config.user);
        }
        if (mConnection != null) {
            mContext.unbindService(mConnection);
        }
        if (mInterface != null && !mInterface.equals(interfaze)) {
            jniReset(mInterface);
        }
        mConnection = connection;
        mInterface = interfaze;
    } catch (RuntimeException e) {
        updateState(DetailedState.FAILED, "establish");
        IoUtils.closeQuietly(tun);
        throw e;
    }
    Log.i(TAG, "Established by " + config.user + " on " + mInterface);
    // Fill more values.
    config.user = mPackage;
    config.interfaze = mInterface;
    // Override DNS servers and show the notification.
    final long token = Binder.clearCallingIdentity();
    try {
        mCallback.override(config.dnsServers, config.searchDomains);
        showNotification(config, label, bitmap);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
    // TODO: ensure that contract class eventually marks as connected
    updateState(DetailedState.AUTHENTICATING, "establish");
    return tun;
}
Also used : Canvas(android.graphics.Canvas) ApplicationInfo(android.content.pm.ApplicationInfo) Drawable(android.graphics.drawable.Drawable) ServiceConnection(android.content.ServiceConnection) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) RemoteException(android.os.RemoteException) ResolveInfo(android.content.pm.ResolveInfo) Bitmap(android.graphics.Bitmap) PackageManager(android.content.pm.PackageManager) ParcelFileDescriptor(android.os.ParcelFileDescriptor)

Aggregations

ParcelFileDescriptor (android.os.ParcelFileDescriptor)526 IOException (java.io.IOException)199 FileNotFoundException (java.io.FileNotFoundException)136 RemoteException (android.os.RemoteException)127 File (java.io.File)127 FileDescriptor (java.io.FileDescriptor)58 FileOutputStream (java.io.FileOutputStream)58 AssetFileDescriptor (android.content.res.AssetFileDescriptor)44 FileInputStream (java.io.FileInputStream)36 Parcel (android.os.Parcel)35 Uri (android.net.Uri)33 Intent (android.content.Intent)30 Bundle (android.os.Bundle)29 Cursor (android.database.Cursor)27 StorageManager (android.os.storage.StorageManager)25 Request (android.app.DownloadManager.Request)24 Bitmap (android.graphics.Bitmap)22 InputStream (java.io.InputStream)18 ProfilerInfo (android.app.ProfilerInfo)17 Binder (android.os.Binder)17