Example usage for android.content Context getExternalCacheDir

List of usage examples for android.content Context getExternalCacheDir

Introduction

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

Prototype

@Nullable
public abstract File getExternalCacheDir();

Source Link

Document

Returns absolute path to application-specific directory on the primary shared/external storage device where the application can place cache files it owns.

Usage

From source file:org.zywx.wbpalmstar.platform.push.PushRecieveMsgReceiver.java

private Bitmap getIconBitmap(Context context, String iconUrl) {
    try {//from   ww w .  java  2  s . c  o m
        URL uRL = new URL(iconUrl);
        HttpURLConnection connection = (HttpURLConnection) uRL.openConnection();
        String cookie = CookieManager.getInstance().getCookie(iconUrl);
        if (null != cookie) {
            connection.setRequestProperty(SM.COOKIE, cookie);
        }
        connection.connect();
        if (200 == connection.getResponseCode()) {
            InputStream input = connection.getInputStream();
            if (input != null) {
                Environment.getDownloadCacheDirectory();
                File ecd = context.getExternalCacheDir();
                File file = new File(ecd, "pushIcon.png");
                OutputStream outStream = new FileOutputStream(file);
                byte buf[] = new byte[8 * 1024];
                while (true) {
                    int numread = input.read(buf);
                    if (numread == -1) {
                        break;
                    }
                    outStream.write(buf, 0, numread);
                }
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                return bitmap;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.rebo.app.MapLayers.java

void setBaseMap(Context context) {

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

    //Temporary files
    String dbname = preferences.getString("mapDatabase", getDbMapName());

    if (dbname.equals(mMapDatabase) && mBaseLayer != null)
        return;//from   w  w w.ja  va 2s  .com

    TileSource tileSource = null;
    for (Config c : configs)
        if (c.name.equals(getDbMapName()))
            tileSource = c.init();

    if (tileSource == null) {
        tileSource = configs[0].init();
        dbname = getDbMapName();
        preferences.edit().putString("mapDatabase", dbname).apply();
    }

    //Cache could be set with an boolean, S3DB would not work with cache
    if (USE_CACHE) {
        if (tileSource instanceof UrlTileSource) {
            mCache = new TileCache(App.activity, context.getExternalCacheDir().getAbsolutePath(), dbname);
            mCache.setCacheSize(512 * (1 << 10));
            tileSource.setCache(mCache);
        } else {
            mCache = null;
        }
    }

    if (mBaseLayer == null) {
        mBaseLayer = App.map.setBaseMap(tileSource); //Base Layer (almost OPENSCIENCEMAP4)
        if (USE_S3DB && ConnectionHandler.isOnline()) {
            TileSource s3dbTileSource = configs[2].init();
            if (USE_CACHE) {
                mS3dbCache = new TileCache(App.activity, context.getExternalCacheDir().getAbsolutePath(),
                        "s3db.db");
                mS3dbCache.setCacheSize(512 * (1 << 10));
                s3dbTileSource.setCache(mS3dbCache);
            }
            App.map.layers().add(2, new S3DBTileLayer(App.map, s3dbTileSource, true, false));
        } else {
            BuildingLayer.POST_AA = true;
            App.map.layers().add(2, new S3DBLayer(App.map, mBaseLayer));
        }
        App.map.layers().add(3, new LabelLayer(App.map, mBaseLayer));
    } else
        mBaseLayer.setTileSource(tileSource);

    mMapDatabase = dbname;
}

From source file:com.colorchen.qbase.utils.FileUtil.java

/**
 * /* w ww .  j ava 2s .com*/
 * <p>/storage/emulated/0/android/data/com.xxx.xxx/cache</p>
 *
 * @return {@code true}: ?<br>{@code false}: 
 */
public static boolean cleanExternalCache(Context context) {
    return FileUtil.isSDCardEnable() && FileUtil.deleteFilesInDir(context.getExternalCacheDir());
}

From source file:com.colorchen.qbase.utils.FileUtil.java

/**
 * ?//from   w  w  w.  j a  va2 s.c  o m
 *
 * @param context
 * @return
 */
public static String getDiskCacheDir(Context context) {
    String cachePath = null;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            || !Environment.isExternalStorageRemovable()) {
        cachePath = context.getExternalCacheDir().getPath();
    } else {
        cachePath = context.getCacheDir().getPath();
    }
    return cachePath;
}

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

private JSONObject requestAllPaths() throws JSONException {
    Context context = cordova.getActivity();
    JSONObject ret = new JSONObject();
    ret.put("applicationDirectory", "file:///android_asset/");
    ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
    ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
    ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {//from   w  w w.  j ava  2 s.co m
            ret.put("externalApplicationStorageDirectory",
                    toDirUrl(context.getExternalFilesDir(null).getParentFile()));
            ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
            ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
            ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
        } catch (NullPointerException e) {
            /* If external storage is unavailable, context.getExternal* returns null */
            Log.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
        }
    }
    return ret;
}

From source file:com.android.email.mail.store.ImapFolder.java

/**
 * Appends the given messages to the selected folder. This implementation also determines
 * the new UID of the given message on the IMAP server and sets the Message's UID to the
 * new server UID./*from   ww  w  . j a  v  a 2 s . c o  m*/
 * @param message Message
 * @param noTimeout Set to true on manual syncs, disables the timeout after sending the message
 *                  content to the server
 */
@Override
public void appendMessage(final Context context, final Message message, final boolean noTimeout)
        throws MessagingException {
    checkOpen();
    try {
        // Create temp file
        /**
         * We need to know the encoded message size before we upload it, and encoding
         * attachments as Base64, possibly reading from a slow provider, is a non-trivial
         * operation. So we write the contents to a temp file while measuring the size,
         * and then use that temp file and size to do the actual upsync.
         * For context, most classic email clients would store the message in RFC822 format
         * internally, and so would not need to do this on-the-fly.
         */
        final File tempDir = context.getExternalCacheDir();
        final File tempFile = File.createTempFile("IMAPupsync", ".eml", tempDir);
        // Delete here so we don't leave the file lingering. We've got a handle to it so we
        // can still use it.
        final boolean deleteSuccessful = tempFile.delete();
        if (!deleteSuccessful) {
            LogUtils.w(LogUtils.TAG, "Could not delete temp file %s", tempFile.getAbsolutePath());
        }
        final OutputStream tempOut = new FileOutputStream(tempFile);
        // Create output count while writing temp file
        final CountingOutputStream out = new CountingOutputStream(tempOut);
        final EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(out);
        message.writeTo(eolOut);
        eolOut.flush();
        // Create flag list (most often this will be "\SEEN")
        String flagList = "";
        Flag[] flags = message.getFlags();
        if (flags.length > 0) {
            StringBuilder sb = new StringBuilder();
            for (final Flag flag : flags) {
                if (flag == Flag.SEEN) {
                    sb.append(" " + ImapConstants.FLAG_SEEN);
                } else if (flag == Flag.FLAGGED) {
                    sb.append(" " + ImapConstants.FLAG_FLAGGED);
                }
            }
            if (sb.length() > 0) {
                flagList = sb.substring(1);
            }
        }

        mConnection.sendCommand(
                String.format(Locale.US, ImapConstants.APPEND + " \"%s\" (%s) {%d}",
                        ImapStore.encodeFolderName(mName, mStore.mPathPrefix), flagList, out.getCount()),
                false);
        ImapResponse response;
        do {
            final int socketTimeout = mConnection.mTransport.getSoTimeout();
            try {
                // Need to set the timeout to unlimited since we might be upsyncing a pretty
                // big attachment so who knows how long it'll take. It would sure be nice
                // if this only timed out after the send buffer drained but welp.
                if (noTimeout) {
                    // For now, only unset the timeout if we're doing a manual sync
                    mConnection.mTransport.setSoTimeout(0);
                }
                response = mConnection.readResponse();
                if (response.isContinuationRequest()) {
                    final OutputStream transportOutputStream = mConnection.mTransport.getOutputStream();
                    IOUtils.copyLarge(new FileInputStream(tempFile), transportOutputStream);
                    transportOutputStream.write('\r');
                    transportOutputStream.write('\n');
                    transportOutputStream.flush();
                } else if (!response.isTagged()) {
                    handleUntaggedResponse(response);
                }
            } finally {
                mConnection.mTransport.setSoTimeout(socketTimeout);
            }
        } while (!response.isTagged());

        // TODO Why not check the response?

        /*
         * Try to recover the UID of the message from an APPENDUID response.
         * e.g. 11 OK [APPENDUID 2 238268] APPEND completed
         */
        final ImapList appendList = response.getListOrEmpty(1);
        if ((appendList.size() >= 3) && appendList.is(0, ImapConstants.APPENDUID)) {
            String serverUid = appendList.getStringOrEmpty(2).getString();
            if (!TextUtils.isEmpty(serverUid)) {
                message.setUid(serverUid);
                return;
            }
        }

        /*
         * Try to find the UID of the message we just appended using the
         * Message-ID header.  If there are more than one response, take the
         * last one, as it's most likely the newest (the one we just uploaded).
         */
        final String messageId = message.getMessageId();
        if (messageId == null || messageId.length() == 0) {
            return;
        }
        // Most servers don't care about parenthesis in the search query [and, some
        // fail to work if they are used]
        String[] uids = searchForUids(String.format(Locale.US, "HEADER MESSAGE-ID %s", messageId));
        if (uids.length > 0) {
            message.setUid(uids[0]);
        }
        // However, there's at least one server [AOL] that fails to work unless there
        // are parenthesis, so, try this as a last resort
        uids = searchForUids(String.format(Locale.US, "(HEADER MESSAGE-ID %s)", messageId));
        if (uids.length > 0) {
            message.setUid(uids[0]);
        }
    } catch (IOException ioe) {
        throw ioExceptionHandler(mConnection, ioe);
    } finally {
        destroyResponses();
    }
}

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

protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
    Context context = activity.getApplicationContext();
    HashMap<String, String> availableFileSystems = new HashMap<String, String>();

    availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
    availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
    availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
    availableFileSystems.put("root", "/");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {/* ww w.  j a v  a  2  s  .  c  o m*/
            availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
            availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
            availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
        }
    }

    return availableFileSystems;
}

From source file:com.c4mprod.utils.ImageManager.java

private ImageManager(final Context ctx) {

    instance = this;
    mDowloadLooper = new LooperThread();
    mDowloadLooper.start();// w w w .  j  a v a 2 s  .c om
    mUiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mStopped) {
                return;
            }
            ImageDownloadMessageData messageData = (ImageDownloadMessageData) msg.obj;
            View v = messageData.viewRef.get();
            if (v != null && messageData.bitmap != null
                    && messageData == getImageDownloadData(v, messageData.flags)) {
                if (messageData.listerner != null) {
                    messageData.listerner.onImageDownloaded(v, messageData.bitmap);
                } else {
                    if (v instanceof ImageView) {
                        if ((messageData.flags & FLAG_IN_BACKGROUND) != 0) {
                            BitmapDrawable bd = new BitmapDrawable(ctx.getResources(), messageData.bitmap);
                            v.setBackgroundDrawable(bd);
                        } else {
                            ((ImageView) v).setImageBitmap(messageData.bitmap);
                        }
                    } else if (v instanceof ImageButton) {
                        if ((messageData.flags & FLAG_IN_BACKGROUND) != 0) {
                            BitmapDrawable bd = new BitmapDrawable(ctx.getResources(), messageData.bitmap);
                            v.setBackgroundDrawable(bd);
                        } else {
                            ((ImageButton) v).setImageBitmap(messageData.bitmap);
                        }
                    } else { // no src
                        BitmapDrawable bd = new BitmapDrawable(ctx.getResources(), messageData.bitmap);
                        v.setBackgroundDrawable(bd);
                    }

                }
            }
        };
    };

    // create cache dir if needed
    new File(ctx.getExternalCacheDir() + THUMB_FOLDER).mkdirs();
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static File getBestCacheDir(final Context context, final String cacheDirName) {
    if (context == null)
        throw new NullPointerException();
    final File extCacheDir;
    try {/*from   w  w  w.  j av a  2  s  . c o  m*/
        // Workaround for https://github.com/mariotaku/twidere/issues/138
        extCacheDir = context.getExternalCacheDir();
    } catch (final Exception e) {
        return new File(context.getCacheDir(), cacheDirName);
    }
    if (extCacheDir != null && extCacheDir.isDirectory()) {
        final File cacheDir = new File(extCacheDir, cacheDirName);
        if (cacheDir.isDirectory() || cacheDir.mkdirs())
            return cacheDir;
    }
    return new File(context.getCacheDir(), cacheDirName);
}

From source file:org.getlantern.firetweet.util.Utils.java

public static File getBestCacheDir(final Context context, final String cacheDirName) {
    if (context == null)
        throw new NullPointerException();
    final File extCacheDir;
    try {/*from   w ww .ja  v a  2  s  .c o m*/
        // Workaround for https://github.com/mariotaku/firetweet/issues/138
        extCacheDir = context.getExternalCacheDir();
    } catch (final Exception e) {
        Crashlytics.logException(e);
        return new File(context.getCacheDir(), cacheDirName);
    }
    if (extCacheDir != null && extCacheDir.isDirectory()) {
        final File cacheDir = new File(extCacheDir, cacheDirName);
        if (cacheDir.isDirectory() || cacheDir.mkdirs())
            return cacheDir;
    }
    return new File(context.getCacheDir(), cacheDirName);
}