Java Code Examples for android.app.Activity#getCacheDir()

The following examples show how to use android.app.Activity#getCacheDir() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AssetsToCacheDir.java    From MusicPlayer_XiangDa with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 将asset文件写入缓存
 */
public static boolean copyAssetAndWrite(Activity c, String fileName) throws IOException {
    try {
        File cacheDir = c.getCacheDir();
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
        File outFile = new File(cacheDir, fileName);
        if (!outFile.exists()) {
            boolean res = outFile.createNewFile();
            if (!res) {
                return false;
            }
        } else {
            if (outFile.length() > 10) {//表示已经写入一次
                return true;
            }
        }
        InputStream is = c.getAssets().open(fileName);
        FileOutputStream fos = new FileOutputStream(outFile);
        byte[] buffer = new byte[1024];
        int byteCount;
        while ((byteCount = is.read(buffer)) != -1) {
            fos.write(buffer, 0, byteCount);
        }
        fos.flush();
        is.close();
        fos.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 2
Source File: CommonUtility.java    From appcan-android with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void clearAllCacheFile(Activity activity) {
    File folder = activity.getCacheDir();
    try {
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.getName().endsWith(".tmp")) {
                file.delete();
            }
        }
    } catch (Exception e) {
        BDebug.e(TAG, "clearAllCacheFile:" + e.getMessage());
        e.printStackTrace();
    }
}
 
Example 3
Source File: EasyPhotosActivity.java    From imsdk-android with MIT License 4 votes vote down vote up
private void startCrop(Activity context, String source, Intent data) {

        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(source, bitmapOptions);
        if (bitmapOptions.outWidth == -1 || bitmapOptions.outHeight == -1) {
            setResult(RESULT_OK, data);
            finish();
            Log.e("EasyPhotos", "该类型不支持裁剪!");
            return;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH:mm:ss", Locale.getDefault());
        String suffix = source.substring(source.lastIndexOf("."));
        String imageName = "IMG_CROP_%s" + suffix;
        String destinationFileName = String.format(imageName, dateFormat.format(new Date()));

        UCrop.Options options = new UCrop.Options();
        //设置相关颜色
        int statusBarColor = ContextCompat.getColor(this, R.color.easy_photos_status_bar);
        if (ColorUtils.isWhiteColor(statusBarColor)) {
            statusBarColor = Color.LTGRAY;
        }
        options.setStatusBarColor(statusBarColor);
        int barColor = ContextCompat.getColor(this, R.color.easy_photos_bar_primary);
        options.setToolbarColor(barColor);
        int widgetColor = ContextCompat.getColor(this, R.color.easy_photos_fg_primary);
        options.setToolbarWidgetColor(widgetColor);
        options.setActiveWidgetColor(Color.BLACK);
        //options.setLogoColor(Color.TRANSPARENT);
        //设置裁剪质量
        options.setCompressionQuality(Setting.compressQuality);
        //是否圆形裁剪
        options.setCircleDimmedLayer(Setting.isCircle);
        //设置网格相关
        options.setShowCropFrame(Setting.isShowCropCropFrame);
        options.setShowCropGrid(Setting.isShowCropGrid);
        //是否自由裁剪
        options.setFreeStyleCropEnabled(Setting.isFreeStyleCrop);
        //设置title
        options.setToolbarTitle("");
        //隐藏底部控制栏
        options.setHideBottomControls(Setting.isHideUCropControls);

        File cacheFile = new File(context.getCacheDir(), destinationFileName);
        UCrop.of(Uri.fromFile(new File(source)), Uri.fromFile(cacheFile))
                .withAspectRatio(Setting.aspectRatio[0], Setting.aspectRatio[1])
                .withOptions(options)
                .start(context);
    }
 
Example 4
Source File: PhotoEditorActivity.java    From react-native-photo-editor with Apache License 2.0 4 votes vote down vote up
private String getTmpDir(Activity activity) {
    String tmpDir = activity.getCacheDir() + "/react-native-photo-editor";
    new File(tmpDir).mkdir();

    return tmpDir;
}
 
Example 5
Source File: DynamicFontsModule.java    From react-native-dynamic-fonts with MIT License 4 votes vote down vote up
@ReactMethod
public void loadFont(final ReadableMap options, final Callback callback) throws Exception {
  Activity currentActivity = getCurrentActivity();
  if (currentActivity == null) {
    callback.invoke("Invalid activity");
    return;
  }

  String name = (options.hasKey("name")) ? options.getString("name") : null,
         data = (options.hasKey("data")) ? options.getString("data") : null,
         type = null;

  if (name == null || name.length() == 0) {
    callback.invoke("Name property empty");
    return;
  }

  if (data == null || data.length() == 0) {
    callback.invoke("Data property empty");
    return;
  }

  if (("data:").equalsIgnoreCase(data.substring(0, 5))) {
    Integer pos = data.indexOf(',');
    if (pos > 0) {
      String[] encodingParams = data.substring(5, pos).split(";");
      String mimeType = encodingParams[0];

      data = data.substring(pos + 1);

      if (("application/x-font-ttf").equalsIgnoreCase(mimeType) ||
          ("application/x-font-truetype").equalsIgnoreCase(mimeType) ||
          ("font/ttf").equalsIgnoreCase(mimeType)) {
        type = "ttf";
      } else if (("application/x-font-opentype").equalsIgnoreCase(mimeType) ||
                 ("font/opentype").equalsIgnoreCase(mimeType)) {
        type = "otf";
      }
    }
  }

  if (options.hasKey("type"))
    type = options.getString("type");

  if (type == null)
    type = "ttf";

  try {
    byte[] decodedBytes = Base64.decode(data, Base64.DEFAULT);
    File cacheFile = new File(currentActivity.getCacheDir(), "tempFont" + (tempNameCounter++) + type);

    FileOutputStream stream = new FileOutputStream(cacheFile);
    try {
      stream.write(decodedBytes);
    } finally {
      stream.close();
    }

    //Load the font from the temporary file we just created
    Typeface typeface = Typeface.createFromFile(cacheFile);

    if (typeface.isBold())
      name = name + "_bold";

    if (typeface.isItalic())
      name = name + "_italic";

    //Cache the font for react
    ReactFontManager.getInstance().setTypeface(name, typeface.getStyle(), typeface);

    cacheFile.delete();
  } catch(Exception e) {
    callback.invoke(e.getMessage());
  } finally {
    callback.invoke(null, name);
  }
}
 
Example 6
Source File: CommonUtility.java    From appcan-android with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static File createCacheFile(Activity activity) {
    return new File(activity.getCacheDir(), System.currentTimeMillis() + ".tmp");
}
 
Example 7
Source File: ApplicationTest.java    From Man-Man with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void checkLocalArchive() throws InterruptedException {
    final Activity act = mActivityRule.getActivity();

    // first we need to clear archive
    final File localArchive = new File(act.getCacheDir(), "manpages.zip");
    localArchive.delete();

    onView(withText(R.string.local_storage)).perform(click());
    onView(withText(R.string.download_archive)).perform(click());
    onView(withText(android.R.string.ok)).perform(click());

    // wait for local archive to load
    await().atMost(10, TimeUnit.MINUTES).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            final ListView searchList = (ListView) act.findViewById(R.id.local_storage_page_list);
            return searchList.getChildCount() > 0;
        }
    });

    onView(withId(R.id.local_search_edit)).perform(typeText("tar"), closeSoftKeyboard());
    onView(allOf(withText("local:/man1"), hasSibling(withText("tar"))))
            .check(matches(isDisplayed()))
            .perform(click());

    // wait for page to load
    await().atMost(5, TimeUnit.SECONDS).until(new WebViewVisible(act));

    // check one of link names
    onView(withId(R.id.link_list))
            .check(matches(allOf(
                    hasDescendant(withText("SYNOPSIS")),
                    hasDescendant(withText("--blocking-factor")),
                    hasDescendant(withText("--index-file")),
                    hasDescendant(withText("--pax-option")),
                    hasDescendant(withText("--to-command")),
                    hasDescendant(withText("--uncompress")),
                    hasDescendant(withText("-G"))
                            )));
}