Example #1
2
  private synchronized void initWebSettings() {

    if (android.os.Build.VERSION.SDK_INT >= 21) WebView.enableSlowWholeDocumentDraw();

    WebSettings webSettings = getSettings();
    userAgentOriginal = webSettings.getUserAgentString();

    webSettings.setAllowContentAccess(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setAllowFileAccessFromFileURLs(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);

    webSettings.setAppCacheEnabled(true);
    webSettings.setAppCachePath(context.getCacheDir().toString());
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setGeolocationDatabasePath(context.getFilesDir().toString());

    webSettings.setSupportZoom(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);

    webSettings.setDefaultTextEncodingName(BrowserUnit.URL_ENCODING);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      webSettings.setLoadsImagesAutomatically(true);
    } else {
      webSettings.setLoadsImagesAutomatically(false);
    }
  }
Example #2
1
  /** 初始化硬盘缓存 */
  private void initDiskCache() {
    try {
      String cache;
      if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
          || !Environment.isExternalStorageRemovable()) {
        if (context.getExternalCacheDir() != null) {
          cache = context.getExternalCacheDir().getPath();
          Log.i("Test", "SD");
        } else {
          throw new Exception("SD卡连接错误");
        }
      } else {
        cache = context.getCacheDir().getPath();
        Log.i("Test", "mobilephone");
      }

      /** SD卡数据缓存目录 */
      String dataFileName = "indoor_data";

      cache = cache + File.separator + dataFileName;
      File fileDir = new File(cache);
      if (!fileDir.exists()) {
        if (fileDir.mkdirs()) {
          Log.e("Test", "创建目录: " + fileDir.getAbsolutePath());
        } else {
          Log.e("Test", "创建目录失败");
        }
      } else {
        Log.e("Test", "目录: " + fileDir.getAbsolutePath());
      }
      diskLruCache = DiskLruCache.open(fileDir, getAppVersion(context), 1, DISK_CACHE_DEFAULT_SIZE);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #3
0
    public BaseCache build(Context context) {

      BaseCache cache = new BaseCache();
      File dir = context.getExternalCacheDir();

      if (dir != null && cache.validateLocation(dir)) {
        cache.mDiskCacheLocation = TextUtils.isEmpty(type) ? dir : new File(dir, type);
      } else {
        cache.mDiskCacheLocation =
            TextUtils.isEmpty(type) ? context.getCacheDir() : new File(context.getCacheDir(), type);
      }

      try {
        cache.mDiskCache =
            DiskLruCache.open(
                cache.mDiskCacheLocation,
                0,
                1,
                Constants.DEFAULT_DISK_CACHE_MAX_SIZE_MB * Constants.MEGABYTE);
      } catch (IOException e) {
        e.printStackTrace();
      }

      cache.mDiskCacheEditLocks = new HashMap<>();
      cache.mDiskCacheFlusherExecutor =
          new ScheduledThreadPoolExecutor(Constants.DEFAULT_DISK_CACHE_MAX_SIZE_MB);
      cache.mDiskCacheFlusherRunnable = new DiskCacheFlushRunnable(cache.mDiskCache);
      cache.mTempDir = context.getCacheDir();
      return cache;
    }
Example #4
0
 public static void initializeSettings(WebSettings settings, Context context) {
   settings.setJavaScriptEnabled(true);
   settings.setJavaScriptCanOpenWindowsAutomatically(true);
   settings.setUserAgentString(settings.getUserAgentString() + DB.USER_AGENT);
   settings.setSupportMultipleWindows(true);
   settings.setSaveFormData(false);
   settings.setSavePassword(false); // 设置为true,系统会弹出AlertDialog确认框
   if (API < 18) {
     settings.setAppCacheMaxSize(Long.MAX_VALUE);
   }
   if (API < 17) {
     settings.setEnableSmoothTransition(true);
   }
   if (API < 19) {
     settings.setDatabasePath(context.getFilesDir().getAbsolutePath() + "/databases");
   }
   settings.setDomStorageEnabled(true);
   settings.setAppCachePath(context.getCacheDir().toString());
   settings.setAppCacheEnabled(true);
   settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
   settings.setGeolocationDatabasePath(context.getCacheDir().getAbsolutePath());
   settings.setAllowFileAccess(true);
   settings.setDatabaseEnabled(true);
   settings.setSupportZoom(true);
   settings.setBuiltInZoomControls(true);
   settings.setDisplayZoomControls(false);
   settings.setAllowContentAccess(true);
   settings.setDefaultTextEncodingName("utf-8");
   /*if (API > 16) {
   	settings.setAllowFileAccessFromFileURLs(false);
   	settings.setAllowUniversalAccessFromFileURLs(false);
   }*/
 }
Example #5
0
 public static String picDir(int hash, Context context) {
   File cacheDir = context.getCacheDir();
   if (cacheDir == null) cacheDir = context.getFilesDir();
   File picDir = new File(context.getCacheDir().getPath() + "/" + hash);
   picDir.mkdirs();
   return picDir.getPath();
 }
Example #6
0
  public static File getCacheStorageDirectory(boolean allowExternal) {
    File directory;
    Context context = MyApplication.getAppContext();
    if (allowExternal) {
      directory = context.getExternalCacheDir();
      if (directory == null) {
        directory = context.getCacheDir();
      }
    } else directory = context.getCacheDir();

    return directory;
  }
Example #7
0
 /**
  * @param c
  * @return 返回cache目录 如: /data/data/com.xhmm.BeautyChina/cache/
  */
 public static String getInternalCacheDir(Context c) {
   File f = c.getCacheDir();
   if (f != null) {
     f.mkdirs();
   }
   return f.getAbsolutePath() + File.separator;
 }
Example #8
0
  public synchronized void pruneCache() {

    try {

      final HashSet<Long> currentFiles = new HashSet<Long>(128);

      final File externalCacheDir = context.getExternalCacheDir();
      final File internalCacheDir = context.getCacheDir();

      if (externalCacheDir != null) {
        getCacheFileList(externalCacheDir, currentFiles);
      }

      if (internalCacheDir != null) {
        getCacheFileList(internalCacheDir, currentFiles);
      }

      final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
      final HashMap<Integer, Long> maxAge = PrefsUtility.pref_cache_maxage(context, prefs);

      final LinkedList<Long> filesToDelete = dbManager.getFilesToPrune(currentFiles, maxAge, 72);
      for (final long id : filesToDelete) {
        fileDeletionQueue.enqueue(id);
      }

    } catch (Throwable t) {
      BugReportActivity.handleGlobalError(context, t);
    }
  }
 public static String getTotalCacheSize(Context context) throws Exception {
   long cacheSize = getFolderSize(context.getCacheDir());
   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     cacheSize += getFolderSize(context.getExternalCacheDir());
   }
   return getFormatSize(cacheSize);
 }
  /**
   * Read the file by specified cache key.
   *
   * <p>Cache key is converted into file name. While this procedure different cache keys can point
   * the same file. Need to try to used letter and numbers where possible.
   *
   * @param key the cache key.
   * @return the stream from found file or null if nothing was found by cache key.
   */
  public InputStream read(String key) {
    final File cacheDir = context.getCacheDir();
    final String fileName = convertToFileName(key);
    final File file = new File(cacheDir, fileName);

    return readFileContent(file);
  }
    public Drawable loadImageFromUrl(Context context, String imageUrl) {
      Drawable drawable = null;

      if (imageUrl == null) return null;
      String fileName = "";

      // 获取url中图片的文件名与后缀
      if (imageUrl != null && imageUrl.length() != 0) {
        fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
      }

      File file = new File(context.getCacheDir(), fileName);

      if (!file.exists() && !file.isDirectory()) {
        try {
          FileOutputStream fos = new FileOutputStream(file);
          InputStream is = new URL(imageUrl).openStream();
          int data = is.read();
          while (data != -1) {
            fos.write(data);
            data = is.read();
          }
          fos.close();
          is.close();

          drawable = Drawable.createFromPath(file.toString());
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else {
        // System.out.println(file.isDirectory() + " " + file.getName());
        drawable = Drawable.createFromPath(file.toString());
      }
      return drawable;
    }
  /**
   * Check if specified key is already stored in the cache.
   *
   * @param key the cache key.
   * @return true if stored, otherwise false.
   */
  public boolean containsKey(String key) {
    final File cacheDir = context.getCacheDir();
    final String fileName = convertToFileName(key);
    final File file = new File(cacheDir, fileName);

    return file.exists();
  }
 public static File getAppCacheDir(Context context) {
   File file = context.getExternalCacheDir();
   if (file == null) {
     file = context.getCacheDir();
   }
   return file;
 }
  protected String doInBackground(String... urls) {
    String name = mVideo.substring(mVideo.lastIndexOf('/') + 1);

    if (mVideo == null || mVideo.equals("null") || mVideo.equals("")) {
      return null;
    }

    File lPictureFile = new File(mContext.getCacheDir() + "/" + name);

    if (!lPictureFile.exists()) {
      try {
        InputStream inputStream = new java.net.URL(mVideo).openStream();
        OutputStream outputStream = new FileOutputStream(lPictureFile);
        BufferedInputStream bin = new BufferedInputStream(inputStream);
        BufferedOutputStream bout = new BufferedOutputStream(outputStream);

        int bytesRead = 0;
        byte[] buffer = new byte[1024];

        while ((bytesRead = bin.read(buffer, 0, 1024)) != -1) {
          bout.write(buffer, 0, bytesRead);
        }

        bout.close();
        bin.close();
        outputStream.close();
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
    }

    return lPictureFile.getAbsolutePath().toString();
  }
Example #15
0
  /**
   * Enable caching to the phone's internal storage or SD card.
   *
   * @param context the current context
   * @param storageDevice where to store the cached files, either {@link #DISK_CACHE_INTERNAL} or
   *     {@link #DISK_CACHE_SDCARD})
   * @return
   */
  public boolean enableDiskCache(Context context, int storageDevice) {
    Context appContext = context.getApplicationContext();

    String rootDir = null;
    if (storageDevice == DISK_CACHE_SDCARD
        && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
      // SD-card available
      rootDir =
          Environment.getExternalStorageDirectory().getAbsolutePath()
              + "/"
              + appContext.getPackageName();
    } else {
      rootDir = appContext.getCacheDir().getAbsolutePath();
    }

    this.diskCacheDirectory =
        rootDir + "/cachefu/" + StringSupport.underscore(name.replaceAll("\\s", ""));
    File outFile = new File(diskCacheDirectory);
    outFile.mkdirs();

    isDiskCacheEnabled = outFile.exists();

    if (!isDiskCacheEnabled) {
      Log.w(LOG_TAG, "Failed creating disk cache directory " + diskCacheDirectory);
    } else {
      Log.d(name, "enabled write through to " + diskCacheDirectory);
    }

    return isDiskCacheEnabled;
  }
Example #16
0
  /**
   * Load Boot image from network if it does not exist in the cache, and then store it.
   *
   * @param bootUrl The URL to load the image.
   */
  public void loadAndStoreBootImage(String bootUrl) {
    if (TextUtils.isEmpty(bootUrl)) {
      return;
    }

    SharedStore sharedStore = new SharedStore(mContext, null);
    String bootUrlSaved = sharedStore.getString("boot_url", null);

    File bootCacheDirectory = mContext.getCacheDir();
    String imageName = "boot";
    File imageFile = new File(bootCacheDirectory, imageName);
    FastBitmapDrawable drawable = getImageFromCache(bootCacheDirectory, imageName);
    if (bootUrl.equals(bootUrlSaved) && drawable != null) {
      // same url and downloaded
      return;
    }

    int orientation = mContext.getResources().getConfiguration().orientation;
    DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
      width = metrics.heightPixels;
      height = metrics.widthPixels;
    }

    Bitmap bootImage = loadImage(bootUrl, true);
    if (bootImage != null) {
      if (imageFile.exists()) {
        imageFile.delete();
      }
      putBootImageToCache(bootImage, width, height, imageName, bootCacheDirectory);
      sharedStore.putString("boot_url", bootUrl);
    }
  }
Example #17
0
  /**
   * Load LOGO image from network if it does not exist in the cache, and then store it.
   *
   * @param logoUrl The URL to load the LOGO image.
   */
  public void loadAndStoreLogoImage(String logoUrl) {
    if (TextUtils.isEmpty(logoUrl)) {
      return;
    }

    SharedStore sharedStore = new SharedStore(mContext, null);

    String logoUrlSaved = sharedStore.getString("logo_url", null);

    File logoCacheDir = mContext.getCacheDir();
    String imageName = "logo";
    File imageFile = new File(logoCacheDir, imageName);
    FastBitmapDrawable drawable = getImageFromCache(logoCacheDir, imageName);
    if (drawable != null && logoUrl.equals(logoUrlSaved)) {
      // same url and downloaded
      return;
    }

    DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
    int width = (int) (172 * metrics.density);
    int height = (int) (44 * metrics.density);

    Bitmap logoImage = loadImage(logoUrl, true);
    if (logoImage != null) {
      imageFile.delete();
      putImageToCache(logoImage, width, height, imageName, logoCacheDir, true);
      sharedStore.putString("logo_url", logoUrl);
    }
  }
Example #18
0
 public static Bitmap getUserImage(final Context context) {
   if (context != null) {
     return BitmapFactory.decodeFile(context.getCacheDir().getPath() + "/userProfilePicture");
   } else {
     return null;
   }
 }
 /**
  * Create image getter for context
  *
  * @param context
  */
 @Inject
 public HttpImageGetter(Context context) {
   this.context = context;
   dir = context.getCacheDir();
   width = ServiceUtils.getDisplayWidth(context);
   loading = new LoadingImageGetter(context, 24);
 }
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
   *
   * @param context A {@link Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @return A started {@link RequestQueue} instance.
   */
  public synchronized void init(Context context, HttpStack stack) {
    File cacheDir = null;
    String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED) && context.getExternalCacheDir().exists())
      cacheDir = new File(context.getExternalCacheDir(), DEFAULT_CACHE_DIR);
    else cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
    String userAgent = "com.sohu.focus";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "Android/v_" + info.versionCode + ",build/" + Build.VERSION.RELEASE;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
      } else {
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }
    diskCache = new DiskBasedCache(cacheDir);
    Network network = new BasicNetwork(stack);
    queue = new RequestQueue(diskCache, network);
    queue.start();

    int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 8);
    memoryCache = new LruMemoryCache(memoryCacheSize);
    imageLoader = new ImageLoader(queue, memoryCache);
  }
Example #21
0
  public AsyncImageLoader(Context context) {
    handler = new Handler();
    startThreadPoolIfNecessary();

    String defaultDir = context.getCacheDir().getAbsolutePath();
    setCachedDir(defaultDir);
  }
Example #22
0
  private ImageCache(Context context) {
    cachedir = new File(context.getCacheDir(), "img");
    cachedir.mkdirs();
    File[] files = cachedir.listFiles();
    if (files != null) {
      for (File file : files) {
        if (file.getName().startsWith("tmp")
            || System.currentTimeMillis() - file.lastModified() > MAX_FILECACHE_AGE) {
          file.delete();
        } else {
          filecachelist.add(file);
          filecachemap.put(file.getName(), file);
          filecachesize += file.length();
        }
      }
      Collections.sort(
          filecachelist,
          new Comparator<File>() {
            @Override
            public int compare(File file1, File file2) {
              return (int) (file1.lastModified() - file2.lastModified());
            }
          });
    }

    // Create threads
    for (int i = 0; i < MAX_THREADS; i++) {
      BitmapDownloaderThread thread = new BitmapDownloaderThread();
      threads.add(thread);
      thread.setPriority(Thread.NORM_PRIORITY - 1);
      thread.start();
    }
  }
 private static String getUniqueTempFileName(Context context, String inputFilename) {
   File directory = new File(context.getCacheDir().getAbsolutePath());
   String fullpath = null;
   if (inputFilename == null || inputFilename.length() == 0) {
     inputFilename = "temp.ismv";
   }
   if (directory != null) {
     if (!directory.exists()) {
       if (!directory.mkdirs()) {
         // Should never fail, if it does, try to use it anyway as we
         // need a private dir
       }
     }
     String filename;
     if (!new File(directory, inputFilename).exists()) {
       filename = inputFilename;
     } else {
       String name = inputFilename.replaceAll("\\.[^\\.]*", "");
       String ext = inputFilename.replaceAll(".*\\.", ".");
       long count = 0;
       do {
         count--;
         filename = name + count + ext;
       } while (new File(directory, filename).exists());
     }
     fullpath = directory + File.separator + filename;
   }
   return fullpath;
 }
  /**
   * Store the file by specified cache key.
   *
   * <p>Cache key is converted into file name. While this procedure different cache keys can point
   * the same file. Need to try to used letter and numbers where possible.
   *
   * @param key the cache key.
   * @param content the content to save in cache.
   * @return true if was saved successfully.
   */
  public boolean store(String key, InputStream content) {
    final File cacheDir = context.getCacheDir();
    final String fileName = convertToFileName(key);
    final File file = new File(cacheDir, fileName);

    return writeFileContent(file, content);
  }
  /**
   * 保存Bitmap到手机缓存
   *
   * @param bm
   * @param savePath
   * @param fileName
   * @param context
   */
  public void saveBitmapToMobileCache(
      Bitmap bm, String savePath, String fileName, Context context) {
    if (bm == null) {
      Log.w(TAG, " trying to savenull bitmap");
      return;
    }

    File path = context.getCacheDir();

    File fileFolder = new File(path.getPath() + "/" + savePath);

    if (!fileFolder.exists()) {
      fileFolder.mkdirs();
    }

    File saveFile = new File(fileFolder.getPath() + "/" + fileName);

    try {
      if (!saveFile.exists()) {
        saveFile.createNewFile();
        OutputStream outStream = new FileOutputStream(saveFile);
        bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);

        outStream.flush();
        outStream.close();
        Log.e("saveFile", saveFile.length() + "");
        Log.i(TAG, "Image saved tosd");
      }
    } catch (Exception e) {
      Log.w(TAG, e.getMessage());
    }
  }
  @Override
  protected void attachBaseContext(Context context) {

    mIncrementalDeploymentDir = getIncrementalDeploymentDir(context) + '/';

    instantiateRealApplication(
        context.getCacheDir(),
        context.getApplicationInfo().nativeLibraryDir,
        context.getApplicationInfo().dataDir);

    // This is called from ActivityThread#handleBindApplication() -> LoadedApk#makeApplication().
    // Application#mApplication is changed right after this call, so we cannot do the monkey
    // patching here. So just forward this method to the real Application instance.
    super.attachBaseContext(context);

    if (real_application_not_instantiated) // it is in the bootstrap process with Seppuku.
    return;

    try {
      Method attachBaseContext =
          ContextWrapper.class.getDeclaredMethod("attachBaseContext", Context.class);
      attachBaseContext.setAccessible(true);
      attachBaseContext.invoke(realApplication, context);

    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }
Example #27
0
  public static void LoadApplication(Context context, String runtimeDataDir, String[] apks) {
    synchronized (lock) {
      if (!initialized) {
        System.loadLibrary("monodroid");
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage() + "-" + locale.getCountry();
        String filesDir = context.getFilesDir().getAbsolutePath();
        String cacheDir = context.getCacheDir().getAbsolutePath();
        String dataDir = context.getApplicationInfo().dataDir + "/lib";
        ClassLoader loader = context.getClassLoader();

        Runtime.init(
            language,
            apks,
            runtimeDataDir,
            new String[] {
              filesDir, cacheDir, dataDir,
            },
            loader,
            new java.io.File(
                    android.os.Environment.getExternalStorageDirectory(),
                    "Android/data/" + context.getPackageName() + "/files/.__override__")
                .getAbsolutePath(),
            MonoPackageManager_Resources.Assemblies);
        initialized = true;
      }
    }
  }
 private void deleteExpiredCacheFiles() {
   File[] files = mContext.getCacheDir().listFiles();
   for (int i = 0; i < files.length; i++) {
     Log.d(TAG, "deleting: " + files[i].getAbsolutePath());
     files[i].delete();
   }
 }
Example #29
0
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
   *
   * @param context A {@link Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @return A started {@link RequestQueue} instance.
   */
  public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
      } else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
        // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
  }
Example #30
0
  private String getCachedData(Context context) {
    try {
      String filename = "get_items:" + categoryId.toString();
      File cacheDir = context.getCacheDir();
      File cacheFile = new File(cacheDir, filename);

      if (!cacheFile.exists()) {
        return null;
      }

      Long modBefore = new Date().getTime() - cacheFile.lastModified();
      if (modBefore > 3600 * 1000) {
        return null;
      }

      BufferedReader reader = new BufferedReader(new FileReader(cacheFile));
      String line;
      String content = "";
      while ((line = reader.readLine()) != null) {
        content = content.concat(line);
      }

      return content;

    } catch (Exception e) {
      return null;
    }
  }