Example usage for android.content Context getDir

List of usage examples for android.content Context getDir

Introduction

In this page you can find the example usage for android.content Context getDir.

Prototype

public abstract File getDir(String name, @FileMode int mode);

Source Link

Document

Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

Usage

From source file:com.android.build.gradle.internal.incremental.fixture.ClassEnhancement.java

private static Map<String, ClassLoader> setUpEnhancedClassLoaders(final ClassLoader mainClassLoader,
        final Map<String, File> compileOutputFolders, final boolean tracing) {
    return Maps.transformEntries(compileOutputFolders, new Maps.EntryTransformer<String, File, ClassLoader>() {
        @Override/*from  w  w w  .j  a  v a  2s . com*/
        public ClassLoader transformEntry(@Nullable String patch, @Nullable File compileOutputFolder) {
            Context context = InstrumentationRegistry.getContext();
            File optimizedDir = new ContextCompat().getCodeCacheDir(context);

            try {
                InputStream is = context.getAssets().open(compileOutputFolder.getPath() + "/classes.dex");
                File output;
                try {
                    File patchDir = new File(context.getDir("patches", Context.MODE_PRIVATE), patch);
                    patchDir.mkdir();
                    output = new File(patchDir, patch + ".dex");

                    Files.asByteSink(output).writeFrom(is);
                } finally {
                    is.close();
                }

                return new DexClassLoader(output.getAbsolutePath(), optimizedDir.getAbsolutePath(), null,
                        ClassEnhancement.class.getClassLoader());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:org.zywx.wbpalmstar.engine.EUtil.java

public static DexClassLoader loadDex(Context ctx, String dexAssertPath) {
    int index = dexAssertPath.lastIndexOf('/');
    if (index < 0) {
        return null;
    }//from  w w w  . j  a  va  2 s . c o  m
    String dexName = dexAssertPath.substring(index);
    String dexPath = ctx.getDir("dex", Context.MODE_PRIVATE).getAbsolutePath() + dexName;
    File f = new File(dexPath);
    if (!f.exists()) {
        boolean ok = copyDex(ctx, dexAssertPath, dexPath);
        if (!ok) {
            return null;
        }
    }
    String dexOutputDir = ctx.getDir("outdex", Context.MODE_PRIVATE).getAbsolutePath();
    DexClassLoader cl = new DexClassLoader(dexPath, dexOutputDir, null, ctx.getClassLoader());
    return cl;
}

From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

/**
 * This method saves the string content to the internal storage.
 *
 * @param applicationContext the application context
 * @param dirName            the directory name, e.g., "configDir"
 * @param fileName           the name of the file
 * @param str                the file content as a string
 * @param mode               the mode, e.g., Context.MODE_PRIVATE
 * @return true on success, false otherwise
 *///from  w w  w . j a va 2 s.  c  o  m
public static boolean saveStringContentToInternalStorage(Context applicationContext, String dirName,
        String fileName, String str, int mode) {
    File directory = applicationContext.getDir(dirName, mode);
    File myPath = new File(directory, fileName);
    try {
        FileWriter out = new FileWriter(myPath);
        out.write(str);
        out.flush();
        out.close();
        return true;
    } catch (IOException e) {
        Log.e(TAG, "Failed to write the content to the file", e);
    }
    return false;
}

From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

/**
 * This method saves the bitmap to the internal storage.
 *
 * @param applicationContext the application context
 * @param dirName            the directory name, e.g., "imageDir"
 * @param imageName          the name of the image
 * @param bitmapImage        the image as a bitmap
 * @param mode               the mode, e.g., Context.MODE_PRIVATE
 * @param format             the format//from w  w w . j av a  2 s.  c  om
 * @param quality            the quality
 * @return the absolute path to the directory where the image is stored
 */
@NonNull
public static String saveBitmapToInternalStorage(Context applicationContext, String dirName, String imageName,
        Bitmap bitmapImage, int mode, Bitmap.CompressFormat format, int quality) {
    File directory = applicationContext.getDir(dirName, mode);
    File myPath = new File(directory, imageName);
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(myPath);
        bitmapImage.compress(format, quality, fos);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.e(TAG, "Failed to write the bitmap to the file", e);
    }
    return directory.getAbsolutePath();
}

From source file:com.itsherpa.andg.imageloader.ImageCache.java

/**
 * Get the external app cache directory.
 * //from w  ww.  ja  va  2s . c  o m
 * @param context
 *            The context to use
 * @return The external cache dir
 */
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
    if (Utils.hasFroyo()) {
        File file = context.getExternalCacheDir();
        if (file == null) {
            // error on Sky with sdcard is not mounted
            return context.getDir("cache", Context.MODE_PRIVATE);
        }
        return file;
    }

    // Before Froyo we need to construct the external cache dir ourselves
    final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
    return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}

From source file:com.hivewallet.androidclient.wallet.AddressBookProvider.java

/**
 * Resizes the provided bitmap and stores it in private storage, returning a URI to it.
 * It will be deleted on the next clean up cycle, unless marked as permanent in the mean time.  */
public static Uri storeBitmap(@Nonnull Context context, @Nonnull Bitmap bitmap) {
    if (bitmap == null)
        return null;

    Bitmap bitmapScaled = ensureReasonableSize(bitmap);
    if (bitmapScaled == null)
        return null;

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    bitmapScaled.compress(CompressFormat.PNG, 100, outStream);
    byte[] photoScaled = outStream.toByteArray();

    Uri photoUri = null;//w ww.  ja  va2s . c o m
    try {
        /* for some reason calling DigestUtils.sha1Hex() does not work on Android */
        String hash = new String(Hex.encodeHex(DigestUtils.sha1(photoScaled)));

        /* create photo asset and database entry */
        File dir = context.getDir(Constants.PHOTO_ASSETS_FOLDER, Context.MODE_PRIVATE);
        File photoAsset = new File(dir, hash + ".png");
        photoUri = Uri.fromFile(photoAsset);
        boolean alreadyPresent = AddressBookProvider.insertOrUpdatePhotoUri(context, photoUri);
        if (!alreadyPresent) {
            FileUtils.writeByteArrayToFile(photoAsset, photoScaled);
            log.info("Saved photo asset with uri {}", photoUri);
        }

        /* use opportunity to clean up photo assets */
        List<Uri> stalePhotoUris = AddressBookProvider.deleteStalePhotoAssets(context);
        for (Uri stalePhotoUri : stalePhotoUris) {
            File stalePhotoAsset = new File(stalePhotoUri.getPath());
            FileUtils.deleteQuietly(stalePhotoAsset);
            log.info("Deleting stale photo asset with uri {}", stalePhotoUri);
        }
    } catch (IOException ignored) {
    }

    return photoUri;
}

From source file:com.quantcast.measurement.service.QCPolicy.java

private void savePolicy(Context context, String policy) {
    File base = context.getDir(POLICY_DIRECTORY, Context.MODE_PRIVATE);
    File policyFile = new File(base, POLICY_FILENAME);
    FileOutputStream stream = null;
    try {/*from   www  .  j av a2  s. c om*/
        stream = new FileOutputStream(policyFile);
        stream.write(policy.getBytes());
    } catch (Exception e) {
        QCLog.e(TAG, "Could not write policy", e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.quantcast.measurement.service.QCPolicy.java

private boolean checkPolicy(Context context, boolean force) {
    boolean retval = false;
    File base = context.getDir(POLICY_DIRECTORY, Context.MODE_PRIVATE);
    File policyFile = new File(base, POLICY_FILENAME);
    if (policyFile.exists()) {
        //check how old it is
        long date = policyFile.lastModified();
        FileInputStream input = null;
        try {/*from  w ww . ja va 2 s. c o  m*/
            input = new FileInputStream(policyFile);
            String policy = readStreamToString(input);
            retval = parsePolicy(policy);
            //check if it should be updated
            retval = retval && (force || ((System.currentTimeMillis() - date) < POLICY_CACHE_LENGTH));
        } catch (Exception e) {
            QCLog.e(TAG, "Could not read from policy cache", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
    return retval;

}

From source file:com.galactogolf.genericobjectmodel.levelloader.LevelSet.java

public void saveToInternalStorage(Context context) throws LevelSavingException {
    File dir = context.getDir(GameConstants.LOCATION_OF_LEVELS_CREATED_BY_USER, Context.MODE_PRIVATE);
    File f = new File(dir, this.getFilename());
    this.saveToFile(f);

}

From source file:csh.cryptonite.Cryptonite.java

public static void cleanCache(Context context) {
    /* Delete directories */
    deleteDir(context.getFilesDir());//from   w  w  w . j  a  v  a  2s.  c o  m
    deleteDir(context.getDir(DirectorySettings.BROWSEPNT, Context.MODE_PRIVATE));
    deleteDir(context.getDir(DirectorySettings.DROPBOXPNT, Context.MODE_PRIVATE));
    deleteDir(DirectorySettings.INSTANCE.openDir);
    deleteDir(DirectorySettings.INSTANCE.readDir);
}