Example usage for android.content Context getCacheDir

List of usage examples for android.content Context getCacheDir

Introduction

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

Prototype

public abstract File getCacheDir();

Source Link

Document

Returns the absolute path to the application specific cache directory on the filesystem.

Usage

From source file:com.moki.touch.fragments.views.WebContent.java

private void configureWebView(Context context) {
    if (!userAgent.equals("default")) {
        webView.getSettings().setUserAgentString(userAgent);
    }/*w  ww .j av  a 2s  .  c o  m*/
    webView.getSettings().setJavaScriptEnabled(true);
    // Set cache size to 32 mb by default. should be more than enough
    webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 32);
    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

    String appCachePath = context.getCacheDir().getAbsolutePath();
    webView.getSettings().setAppCachePath(appCachePath);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    webView.setWebViewClient(new CustomClient());
    if (showProgressBar) {
        webView.setWebChromeClient(new CustomChromeClient());
    }
}

From source file:com.juick.android.JuickMessagesAdapter.java

public static @Nullable File getDestFile(Context ctx, @NotNull String url) {
    if (url == null)
        return null;
    if (url.startsWith("file://")) {
        return new File("/" + new URLParser(url).getPathPart());
    } else {/*www  . j  av  a 2  s.  c  o m*/
        File cacheDir = new File(ctx.getCacheDir(), "image_cache");
        cacheDir.mkdirs();
        return new File(cacheDir, urlToFileName(ctx, url));
    }

}

From source file:edu.cmu.cs.diamond.android.Filter.java

public Filter(int resourceId, Context context, String name, String[] args, byte[] blob) throws IOException {
    Resources r = context.getResources();
    String resourceName = r.getResourceEntryName(resourceId);
    File f = context.getFileStreamPath(resourceName);

    if (!f.exists()) {
        InputStream ins = r.openRawResource(resourceId);
        byte[] buf = IOUtils.toByteArray(ins);
        FileOutputStream fos = context.openFileOutput(resourceName, Context.MODE_PRIVATE);
        IOUtils.write(buf, fos);/* w w  w  . j  av a 2 s  . c  o  m*/
        context.getFileStreamPath(resourceName).setExecutable(true);
        fos.close();
    }

    ProcessBuilder pb = new ProcessBuilder(f.getAbsolutePath());
    Map<String, String> env = pb.environment();
    tempDir = File.createTempFile("filter", null, context.getCacheDir());
    tempDir.delete(); // Delete file and create directory.
    if (!tempDir.mkdir()) {
        throw new IOException("Unable to create temporary directory.");
    }
    env.put("TEMP", tempDir.getAbsolutePath());
    env.put("TMPDIR", tempDir.getAbsolutePath());
    proc = pb.start();
    is = proc.getInputStream();
    os = proc.getOutputStream();

    sendInt(1);
    sendString(name);
    sendStringArray(args);
    sendBinary(blob);

    while (this.getNextToken().tag != TagEnum.INIT)
        ;
    Log.d(TAG, "Filter initialized.");
}

From source file:cat.joronya.utils.image.ImageDownloader.java

public ImageDownloader(Context context, String cachedir, String subdir, int requiredSize) {
    this.context = context;
    this.requiredSize = requiredSize;

    File firstCacheDir = null;//from  ww  w.j a va 2 s  .co m
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        if (cachedir == null && "".equals(cachedir))
            firstCacheDir = new File(Environment.getExternalStorageDirectory(), CACHE_DIR);
        else
            firstCacheDir = new File(Environment.getExternalStorageDirectory(), cachedir);
    } else {
        firstCacheDir = context.getCacheDir();
    }

    // el sub cache dir
    cacheDir = new File(firstCacheDir, subdir);
    if (!cacheDir.exists())
        cacheDir.mkdirs();

    // preparem fitxer ".nomedia", pq el MediaScanner no trobi els fitxers
    File nomediaFile = new File(cacheDir, ".nomedia");
    if (!nomediaFile.exists())
        try {
            nomediaFile.createNewFile();
        } catch (IOException e) {
        }
}

From source file:com.android.email.mail.transport.SmtpSenderUnitTests.java

/**
 * Prepare to send a simple attachment//from  ww  w  . j  a  v a2s .  c  o m
 */
private Attachment setupSimpleAttachment(Context context, long messageId, boolean withBody) throws IOException {
    Attachment attachment = new Attachment();
    attachment.mFileName = "the file.jpg";
    attachment.mMimeType = "image/jpg";
    attachment.mSize = 0;
    attachment.mContentId = null;
    attachment.mContentUri = "content://com.android.email/1/1";
    attachment.mMessageKey = messageId;
    attachment.mLocation = null;
    attachment.mEncoding = null;

    if (withBody) {
        // Is there an easier way to set up a temp file?
        InputStream inStream = new ByteArrayInputStream(TEST_STRING.getBytes());
        File cacheDir = context.getCacheDir();
        File tmpFile = File.createTempFile("setupSimpleAttachment", "tmp", cacheDir);
        OutputStream outStream = new FileOutputStream(tmpFile);

        IOUtils.copy(inStream, outStream);
        attachment.mContentUri = "file://" + tmpFile.getAbsolutePath();
    }

    return attachment;
}

From source file:com.mwebster.iemail.mail.transport.SmtpSenderUnitTests.java

/**
 * Prepare to send a simple attachment//from  w  w  w  .  j  ava 2s .c o  m
 */
private Attachment setupSimpleAttachment(Context context, long messageId, boolean withBody) throws IOException {
    Attachment attachment = new Attachment();
    attachment.mFileName = "the file.jpg";
    attachment.mMimeType = "image/jpg";
    attachment.mSize = 0;
    attachment.mContentId = null;
    attachment.mContentUri = "content://com.mwebster.iemail.1/1";
    attachment.mMessageKey = messageId;
    attachment.mLocation = null;
    attachment.mEncoding = null;

    if (withBody) {
        // Is there an easier way to set up a temp file?
        InputStream inStream = new ByteArrayInputStream(TEST_STRING.getBytes());
        File cacheDir = context.getCacheDir();
        File tmpFile = File.createTempFile("setupSimpleAttachment", "tmp", cacheDir);
        OutputStream outStream = new FileOutputStream(tmpFile);

        IOUtils.copy(inStream, outStream);
        attachment.mContentUri = "file://" + tmpFile.getAbsolutePath();
    }

    return attachment;
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

private ParcelFileDescriptor getCacheFileFd(final String name) throws FileNotFoundException {
    if (name == null)
        return null;
    final Context mContext = getContext();
    final File cacheDir = mContext.getCacheDir();
    final File file = new File(cacheDir, name);
    if (!file.exists())
        return null;
    return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}

From source file:com.github.chenxiaolong.dualbootpatcher.settings.RomSettingsUtils.java

public synchronized static boolean updateRamdisk(Context context) {
    Log.d(TAG, "Starting to update ramdisk to " + BuildConfig.VERSION_NAME);

    try {//from   w w w. j av  a2s . c  o  m
        // libmbp's MbtoolUpdater needs to grab a copy of the latest mbtool from the
        // data archive

        PatcherUtils.extractPatcher(context);

        // We'll need to add the ROM ID to the kernel command line
        RomInformation romInfo = RomUtils.getCurrentRom(context);
        if (romInfo == null) {
            Log.e(TAG, "Could not determine current ROM");
            return false;
        }

        String bootImage = RomUtils.getBootImagePath(romInfo.getId());
        File bootImageFile = new File(bootImage);

        // Make sure the kernel was backed up
        if (!bootImageFile.exists()) {
            try {
                SetKernelResult result = MbtoolSocket.getInstance().setKernel(context, romInfo.getId());
                if (result != SetKernelResult.SUCCEEDED) {
                    Log.e(TAG, "Failed to backup boot image before modification");
                    return false;
                }
            } catch (IOException e) {
                Log.e(TAG, "mbtool communication error", e);
                return false;
            }
        }

        String bootImageBackup = bootImage + ".before-ramdisk-update.img";
        File bootImageBackupFile = new File(bootImageBackup);

        try {
            org.apache.commons.io.FileUtils.copyFile(bootImageFile, bootImageBackupFile);
        } catch (IOException e) {
            Log.w(TAG, "Failed to copy " + bootImage + " to " + bootImageBackupFile, e);
        }

        // Create temporary copy of the boot image
        String tmpKernel = context.getCacheDir() + File.separator + "boot.img";
        File tmpKernelFile = new File(tmpKernel);
        try {
            org.apache.commons.io.FileUtils.copyFile(bootImageFile, tmpKernelFile);
        } catch (IOException e) {
            Log.e(TAG, "Failed to copy boot image to temporary file", e);
            return false;
        }

        // Run MbtoolUpdater on the boot image
        String newFile = updateMbtool(context, tmpKernel);
        if (newFile == null) {
            Log.e(TAG, "Failed to patch file!");
            return false;
        }

        // Check if original boot image was patched with loki or bump
        BootImage bi = new BootImage();
        if (!bi.load(tmpKernel)) {
            logLibMbpError(context, bi.getError());
            bi.destroy();
            return false;
        }
        int wasType = bi.wasType();
        boolean hasRomIdFile;

        CpioFile cpio = new CpioFile();
        if (!cpio.load(bi.getRamdiskImage())) {
            logLibMbpError(context, cpio.getError());
            return false;
        }
        hasRomIdFile = cpio.isExists("romid");
        cpio.destroy();

        bi.destroy();

        Log.d(TAG, "Original boot image type: " + wasType);
        Log.d(TAG, "Original boot image had /romid file in ramdisk: " + hasRomIdFile);

        // Overwrite old boot image
        try {
            tmpKernelFile.delete();
            org.apache.commons.io.FileUtils.moveFile(new File(newFile), tmpKernelFile);
        } catch (IOException e) {
            Log.e(TAG, "Failed to move " + newFile + " to " + tmpKernelFile, e);
            return false;
        }

        // Make changes to the boot image if necessary
        if (wasType == Type.LOKI || !hasRomIdFile) {
            bi = new BootImage();
            cpio = new CpioFile();

            try {
                if (!bi.load(tmpKernel)) {
                    logLibMbpError(context, bi.getError());
                    return false;
                }

                if (wasType == Type.LOKI) {
                    Log.d(TAG, "Will reapply loki to boot image");
                    bi.setTargetType(Type.LOKI);

                    File aboot = new File(context.getCacheDir() + File.separator + "aboot.img");

                    MbtoolSocket socket = MbtoolSocket.getInstance();

                    // Copy aboot partition to the temporary file
                    if (!socket.copy(context, ABOOT_PARTITION, aboot.getPath())
                            || !socket.chmod(context, aboot.getPath(), 0644)) {
                        Log.e(TAG, "Failed to copy aboot partition to temporary file");
                        return false;
                    }

                    byte[] abootImage = org.apache.commons.io.FileUtils.readFileToByteArray(aboot);
                    bi.setAbootImage(abootImage);

                    aboot.delete();
                }
                if (!hasRomIdFile) {
                    if (!cpio.load(bi.getRamdiskImage())) {
                        logLibMbpError(context, cpio.getError());
                        return false;
                    }
                    cpio.remove("romid");
                    if (!cpio.addFile(romInfo.getId().getBytes(Charset.forName("UTF-8")), "romid", 0644)) {
                        logLibMbpError(context, cpio.getError());
                        return false;
                    }
                    bi.setRamdiskImage(cpio.createData());
                }

                if (!bi.createFile(tmpKernel)) {
                    logLibMbpError(context, bi.getError());
                    return false;
                }
            } catch (IOException e) {
                Log.e(TAG, "Failed to make changes to boot image", e);
                return false;
            } finally {
                bi.destroy();
                cpio.destroy();
            }
        }

        try {
            org.apache.commons.io.FileUtils.copyFile(tmpKernelFile, bootImageFile);
        } catch (IOException e) {
            Log.e(TAG, "Failed to copy " + tmpKernelFile + " to " + bootImageFile, e);
            return false;
        }

        tmpKernelFile.delete();

        try {
            SwitchRomResult result = MbtoolSocket.getInstance().chooseRom(context, romInfo.getId(), true);
            if (result != SwitchRomResult.SUCCEEDED) {
                Log.e(TAG, "Failed to reflash boot image");
                return false;
            }
        } catch (IOException e) {
            Log.e(TAG, "mbtool communication error", e);
            return false;
        }

        Log.v(TAG, "Successfully updated ramdisk!");

        return true;
    } finally {
        // Save whatever is in the logcat buffer to /sdcard/MultiBoot/ramdisk-update.log
        LogUtils.dump("ramdisk-update.log");
    }
}

From source file:net.olejon.mdapp.MedicationNlhFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*from  w  w w. j a  va 2  s . c om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
    ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_medication_nlh, container, false);

    // Activity
    final Activity activity = getActivity();

    // Context
    final Context context = activity.getApplicationContext();

    // Tools
    final MyTools mTools = new MyTools(context);

    // Arguments
    Bundle bundle = getArguments();

    final String pageUri = bundle.getString("uri");

    // Progress bar
    final ProgressBar progressBar = (ProgressBar) activity
            .findViewById(R.id.medication_toolbar_progressbar_horizontal);

    // Toolbar
    final LinearLayout toolbarSearchLayout = (LinearLayout) activity
            .findViewById(R.id.medication_toolbar_search_layout);
    final EditText toolbarSearchEditText = (EditText) activity.findViewById(R.id.medication_toolbar_search);

    // Web view
    WEBVIEW = (WebView) viewGroup.findViewById(R.id.medication_nlh_content);

    WebSettings webSettings = WEBVIEW.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAppCachePath(context.getCacheDir().getAbsolutePath());
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

    WEBVIEW.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!mTools.isDeviceConnected()) {
                mTools.showToast(getString(R.string.device_not_connected), 0);
                return true;
            } else if (url.matches(".*/[^#]+#[^/]+$")) {
                WEBVIEW.loadUrl(url.replaceAll("#[^/]+$", ""));
                return true;
            } else if (url.matches("^https?://.*?\\.pdf$")) {
                mTools.downloadFile(view.getTitle(), url);
                return true;
            }

            return false;
        }
    });

    WEBVIEW.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);

                toolbarSearchLayout.setVisibility(View.GONE);
                toolbarSearchEditText.setText("");
            }
        }
    });

    if (savedInstanceState == null) {
        WEBVIEW.loadUrl(pageUri);
    } else {
        WEBVIEW.restoreState(savedInstanceState);
    }

    return viewGroup;
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

public static void setPcap(boolean enabled, Context context) {
    File pcap = (enabled ? new File(context.getCacheDir(), "adblocker.pcap") : null);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String r = prefs.getString("pcap_record_size", null);
    if (TextUtils.isEmpty(r))
        r = "64";
    String f = prefs.getString("pcap_file_size", null);
    if (TextUtils.isEmpty(f))
        f = "2";//from   w  w w .  ja  va 2 s . c  om
    int record_size = Integer.parseInt(r);
    int file_size = Integer.parseInt(f) * 1024 * 1024;
    jni_pcap(pcap == null ? null : pcap.getAbsolutePath(), record_size, file_size);
}