Example usage for android.app Activity getCacheDir

List of usage examples for android.app Activity getCacheDir

Introduction

In this page you can find the example usage for android.app Activity getCacheDir.

Prototype

@Override
    public File getCacheDir() 

Source Link

Usage

From source file:Main.java

public static File getCecheFolder(Activity activity) {
    File folder = new File(activity.getCacheDir(), "IMAGECACHE");
    if (!folder.exists()) {
        folder.mkdir();/*  w w  w  . j  av  a2s .c om*/
    }
    return folder;
}

From source file:io.digibyte.tools.qrcode.QRUtils.java

private static File saveToExternalStorage(Bitmap bitmapImage, Activity app) {
    if (app == null) {
        Log.e(TAG, "saveToExternalStorage: app is null");
        return null;
    }//from   w w  w  .java2s  .c  o  m

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    String fileName = "qrcode.jpg";

    bitmapImage.compress(Bitmap.CompressFormat.PNG, 0, bytes);
    File f = new File(app.getCacheDir(), fileName);
    f.setReadable(true, false);
    try {
        boolean a = f.createNewFile();
        if (!a)
            Log.e(TAG, "saveToExternalStorage: createNewFile: failed");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.e(TAG, "saveToExternalStorage: " + f.getAbsolutePath());
    if (f.exists())
        f.delete();

    try {
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            bytes.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return f;
}

From source file:com.ohso.util.ImageHandler.java

public ImageHandler(Activity activity) {
    MEMORY_CLASS = ((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
    MEMORY_CACHE_SIZE = 1024 * 1024 * MEMORY_CLASS / 8; // Use 1/8 the available memory
    mMemoryCache = new LruCache<String, Bitmap>(MEMORY_CACHE_SIZE) {
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight();
        }// w  w  w.  jav  a 2s  .c o  m
    };
    File cacheDir = new File(activity.getCacheDir(), "thumbnails");
    try {
        mDiskCache = DiskLruCache.open(cacheDir, 1, 1, DISK_CACHE_SIZE);
    } catch (IOException e) {
        e.printStackTrace();
    }
    mPixelSize = scaledDIP(IMAGE_DIMENSIONS);
    mPlaceholderParams = new RelativeLayout.LayoutParams((int) mPixelSize, (int) mPixelSize);
    mPlaceholderParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    mPlaceholderParams.topMargin = 0;
}

From source file:org.apache.cordova.file.FileUtils.java

@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);
    this.filesystems = new ArrayList<Filesystem>();

    String tempRoot = null;// w  w w  . ja v a  2  s.  com
    String persistentRoot = null;

    Activity activity = cordova.getActivity();
    String packageName = activity.getPackageName();

    String location = preferences.getString("androidpersistentfilelocation", "internal");

    tempRoot = activity.getCacheDir().getAbsolutePath();
    if ("internal".equalsIgnoreCase(location)) {
        persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/";
        this.configured = true;
    } else if ("compatibility".equalsIgnoreCase(location)) {
        /*
         *  Fall-back to compatibility mode -- this is the logic implemented in
         *  earlier versions of this plugin, and should be maintained here so
         *  that apps which were originally deployed with older versions of the
         *  plugin can continue to provide access to files stored under those
         *  versions.
         */
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
            tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/"
                    + packageName + "/cache/";
        } else {
            persistentRoot = "/data/data/" + packageName;
        }
        this.configured = true;
    }

    if (this.configured) {
        // Create the directories if they don't exist.
        File tmpRootFile = new File(tempRoot);
        File persistentRootFile = new File(persistentRoot);
        tmpRootFile.mkdirs();
        persistentRootFile.mkdirs();

        // Register initial filesystems
        // Note: The temporary and persistent filesystems need to be the first two
        // registered, so that they will match window.TEMPORARY and window.PERSISTENT,
        // per spec.
        this.registerFilesystem(
                new LocalFilesystem("temporary", webView.getContext(), webView.getResourceApi(), tmpRootFile));
        this.registerFilesystem(new LocalFilesystem("persistent", webView.getContext(),
                webView.getResourceApi(), persistentRootFile));
        this.registerFilesystem(new ContentFilesystem(webView.getContext(), webView.getResourceApi()));
        this.registerFilesystem(
                new AssetFilesystem(webView.getContext().getAssets(), webView.getResourceApi()));

        registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity));

        // Initialize static plugin reference for deprecated getEntry method
        if (filePlugin == null) {
            FileUtils.filePlugin = this;
        }
    } else {
        Log.e(LOG_TAG,
                "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
        activity.finish();
    }
}

From source file:com.remobile.file.FileUtils.java

public void initialize() {
    this.filesystems = new ArrayList<Filesystem>();

    String tempRoot = null;/*from   w ww  .  j  a  va2  s . co m*/
    String persistentRoot = null;

    Activity activity = cordova.getActivity();
    String packageName = activity.getPackageName();

    String location = "internal";

    tempRoot = activity.getCacheDir().getAbsolutePath();
    if ("internal".equalsIgnoreCase(location)) {
        persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/";
        this.configured = true;
    } else if ("compatibility".equalsIgnoreCase(location)) {
        /*
         *  Fall-back to compatibility mode -- this is the logic implemented in
         *  earlier versions of this plugin, and should be maintained here so
         *  that apps which were originally deployed with older versions of the
         *  plugin can continue to provide access to files stored under those
         *  versions.
         */
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
            tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/"
                    + packageName + "/cache/";
        } else {
            persistentRoot = "/data/data/" + packageName;
        }
        this.configured = true;
    }

    if (this.configured) {
        // Create the directories if they don't exist.
        File tmpRootFile = new File(tempRoot);
        File persistentRootFile = new File(persistentRoot);
        tmpRootFile.mkdirs();
        persistentRootFile.mkdirs();

        // Register initial filesystems
        // Note: The temporary and persistent filesystems need to be the first two
        // registered, so that they will match window.TEMPORARY and window.PERSISTENT,
        // per spec.
        this.registerFilesystem(
                new LocalFilesystem("temporary", this.getContext(), this.getResourceApi(), tmpRootFile));
        this.registerFilesystem(new LocalFilesystem("persistent", this.getContext(), this.getResourceApi(),
                persistentRootFile));
        this.registerFilesystem(new ContentFilesystem(this.getContext(), this.getResourceApi()));
        this.registerFilesystem(new AssetFilesystem(this.getContext().getAssets(), this.getResourceApi()));

        registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity));

        // Initialize static plugin reference for deprecated getEntry method
        if (filePlugin == null) {
            FileUtils.filePlugin = this;
        }
    } else {
        Log.e(LOG_TAG,
                "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
        activity.finish();
    }
}

From source file:de.j4velin.mapsmeasure.Dialogs.java

/**
 * @param c     the Context//from   w  w  w  .  j  av a2s .com
 * @param trace the current trace of points
 * @return the "save & share" dialog
 */
public static Dialog getSaveNShare(final Activity c, final Stack<LatLng> trace) {
    final Dialog d = new Dialog(c);
    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
    d.setContentView(R.layout.dialog_save);
    d.findViewById(R.id.save).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            final File destination;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO
                    && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                destination = API8Wrapper.getExternalFilesDir(c);
            } else {
                destination = c.getDir("traces", Context.MODE_PRIVATE);
            }

            d.dismiss();
            AlertDialog.Builder b = new AlertDialog.Builder(c);
            b.setTitle(R.string.save);
            final View layout = c.getLayoutInflater().inflate(R.layout.dialog_enter_filename, null);
            ((TextView) layout.findViewById(R.id.location))
                    .setText(c.getString(R.string.file_path, destination.getAbsolutePath() + "/"));
            b.setView(layout);
            b.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        String fname = ((EditText) layout.findViewById(R.id.filename)).getText().toString();
                        if (fname == null || fname.length() < 1) {
                            fname = "MapsMeasure_" + System.currentTimeMillis();
                        }
                        final File f = new File(destination, fname + ".csv");
                        Util.saveToFile(f, trace);
                        d.dismiss();
                        Toast.makeText(c, c.getString(R.string.file_saved, f.getAbsolutePath()),
                                Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(c,
                                c.getString(R.string.error,
                                        e.getClass().getSimpleName() + "\n" + e.getMessage()),
                                Toast.LENGTH_LONG).show();
                    }
                }
            });
            b.create().show();
        }
    });
    d.findViewById(R.id.load).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {

            File[] files = c.getDir("traces", Context.MODE_PRIVATE).listFiles();

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO
                    && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File ext = API8Wrapper.getExternalFilesDir(c);
                // even though we checked the external storage state, ext is still sometims null, accoring to Play Store crash reports
                if (ext != null) {
                    File[] filesExtern = ext.listFiles();
                    File[] allFiles = new File[files.length + filesExtern.length];
                    System.arraycopy(files, 0, allFiles, 0, files.length);
                    System.arraycopy(filesExtern, 0, allFiles, files.length, filesExtern.length);
                    files = allFiles;
                }
            }

            if (files.length == 0) {
                Toast.makeText(c,
                        c.getString(R.string.no_files_found,
                                c.getDir("traces", Context.MODE_PRIVATE).getAbsolutePath()),
                        Toast.LENGTH_SHORT).show();
            } else if (files.length == 1) {
                try {
                    Util.loadFromFile(Uri.fromFile(files[0]), (Map) c);
                    d.dismiss();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(c,
                            c.getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                            Toast.LENGTH_LONG).show();
                }
            } else {
                d.dismiss();
                AlertDialog.Builder b = new AlertDialog.Builder(c);
                b.setTitle(R.string.select_file);
                final DeleteAdapter da = new DeleteAdapter(files, (Map) c);
                b.setAdapter(da, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Util.loadFromFile(Uri.fromFile(da.getFile(which)), (Map) c);
                            dialog.dismiss();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(c,
                                    c.getString(R.string.error,
                                            e.getClass().getSimpleName() + "\n" + e.getMessage()),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });
                b.create().show();
            }
        }
    });
    d.findViewById(R.id.share).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            try {
                final File f = new File(c.getCacheDir(), "MapsMeasure.csv");
                Util.saveToFile(f, trace);
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM,
                        FileProvider.getUriForFile(c, "de.j4velin.mapsmeasure.fileprovider", f));
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                shareIntent.setType("text/comma-separated-values");
                d.dismiss();
                c.startActivity(Intent.createChooser(shareIntent, null));
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(c,
                        c.getString(R.string.error, e.getClass().getSimpleName() + "\n" + e.getMessage()),
                        Toast.LENGTH_LONG).show();
            }
        }
    });
    return d;
}