Example usage for android.os StatFs getAvailableBlocks

List of usage examples for android.os StatFs getAvailableBlocks

Introduction

In this page you can find the example usage for android.os StatFs getAvailableBlocks.

Prototype

@Deprecated
public int getAvailableBlocks() 

Source Link

Usage

From source file:com.wso2.mobile.mdm.api.DeviceInfo.java

/**
*Returns the available internal memory size
*//*from w  w  w.  jav  a  2s  .  co  m*/
public double getAvailableInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    double blockSize = stat.getBlockSize();
    double availableBlocks = stat.getAvailableBlocks();
    return formatSizeGB(availableBlocks * blockSize);
}

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * sdcard.//from ww  w  .j  av  a2 s .  c om
 * 
 * @return the int
 */
@SuppressWarnings("deprecation")
public static int freeSpaceOnSD() {
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat.getBlockSize()) / 1024 * 1024;
    return (int) sdFreeMB;
}

From source file:eu.mhutti1.utils.storage.StorageDevice.java

public Long getAvailableBytes() {
    StatFs statFs = new StatFs(mFile.getPath());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        return statFs.getBlockSizeLong() * statFs.getAvailableBlocksLong();
    } else {/*from w  w  w. j  av a2s. com*/
        return (long) statFs.getBlockSize() * (long) statFs.getAvailableBlocks();
    }
}

From source file:com.wso2.mobile.mdm.api.DeviceInfo.java

/**
*Returns the available external memory size
*//*from  www.  j  a v  a  2 s. c om*/
public double getAvailableExternalMemorySize() {
    if (externalMemoryAvailable()) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        double blockSize = stat.getBlockSize();
        double availableBlocks = stat.getAvailableBlocks();
        return formatSizeGB(availableBlocks * blockSize);
    } else {
        return ERROR;
    }
}

From source file:com.github.piasy.common.android.utils.roms.RomUtil.java

/**
 * Checks if there is enough Space on SDCard
 *
 * @param updateSize Size to Check// w ww  .  j  av a2  s .c o  m
 * @return {@code true} if the Update will fit on SDCard, {@code false} if not enough space on
 * SDCard. Will also return false, if the SDCard is not mounted as read/write
 */
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public boolean enoughSpaceOnSdCard(final long updateSize) {
    boolean ret = false;
    final String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED)) {
        final File path = Environment.getExternalStorageDirectory();
        final StatFs stat = new StatFs(path.getPath());
        final long blockSize = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                ? stat.getBlockSizeLong()
                : stat.getBlockSize();
        final long availableBlocks = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                ? stat.getAvailableBlocksLong()
                : stat.getAvailableBlocks();

        ret = updateSize < availableBlocks * blockSize;
    }

    return ret;
}

From source file:fr.sedona.volley.manager.HttpImageLoader.java

@SuppressLint("NewApi")
private long getDiskCacheSpace(Context context) {
    String cachePath = context.getCacheDir().getPath();
    File diskCacheDir = new File(cachePath);

    if (Build.VERSION.SDK_INT >= 9) {
        return Math.min(diskCacheDir.getFreeSpace() - (1024 * 1024 * 30), (long) 1024 * 1024 * 20);
    }/*from  w ww .ja v a  2s .co m*/
    StatFs statFs = new StatFs(diskCacheDir.getAbsolutePath());
    return (long) Math.min(statFs.getAvailableBlocks() * (long) statFs.getBlockSize() - (1024 * 1024 * 30),
            (long) 1024 * 1024 * 20);
}

From source file:com.error.hunter.ListenService.java

private void generateBugReport(ActivityManager.ProcessErrorStateInfo entry) {

    String condition;//  ww w .j  av a 2  s  .c  om
    badProcess = entry.processName;
    String build = Build.DISPLAY;
    String fingerprint = Build.FINGERPRINT;
    String serial = Build.SERIAL;
    String product = Build.PRODUCT;
    String model = Build.MODEL;

    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    @SuppressWarnings("deprecation")
    long blockSize = stat.getBlockSize();
    @SuppressWarnings("deprecation")
    long availableBlocks = stat.getAvailableBlocks();
    String memory = Formatter.formatFileSize(this, availableBlocks * blockSize).toString();

    MemoryInfo mi = new MemoryInfo();
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(mi);
    long availableMegs = mi.availMem / 1048576L;

    strBuf.append("Problem detected in: ").append(badProcess);
    if (entry.tag != null) {
        strBuf.append(" (").append(entry.tag).append(")");
    }
    strBuf.append("\nDevice product: " + product);
    strBuf.append("\nDevice model: " + model);
    strBuf.append("\nDevice build: " + build);
    strBuf.append("\nDevice fingerprint: " + fingerprint);
    strBuf.append("\nDevice SN: " + serial);
    strBuf.append("\nDevice available RAM (MB): " + availableMegs);
    strBuf.append("\nDevice free phisical memory: " + memory + "\n");
    strBuf.append(getNetworkInfo());
    strBuf.append("\n");

    ActivityManager actvityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> procInfos = actvityManager.getRunningServices(1000);
    Iterator<RunningServiceInfo> taskIter = procInfos.iterator();
    RunningServiceInfo info;
    while (taskIter.hasNext()) {
        info = taskIter.next();
        if (info.process.equals(badProcess)) {
            strBuf.append("\nService " + info.service + " crash count: " + info.crashCount + " active since: "
                    + info.activeSince + " process: " + info.process);
        }
    }
    strBuf.append("\n");
    //android.os.Debug.MemoryInfo[] miPid = activityManager.getProcessMemoryInfo(new int[]{entry.pid}); 
    //String memoryProc = miPid[0].toString();
    //strBuf.append("\nRAM used by process (Process: " + entry.processName + " PID: " + entry.pid +"): " + memoryProc + "MB\n");

    switch (entry.condition) {

    case ActivityManager.ProcessErrorStateInfo.CRASHED:
        condition = "CRASHED";
        getDeviceProcessInfo(badProcess, entry.stackTrace);
        writeLogsToFile(condition, badProcess);
        break;
    case ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING:
        condition = "ANR";
        getDeviceProcessInfo(badProcess, "");
        writeLogsToFile(condition, badProcess);
        break;
    default:
        condition = "<unknown>";
        getDeviceProcessInfo(badProcess, entry.stackTrace);
        writeLogsToFile(condition, badProcess);
        break;
    }
}

From source file:com.fallahpoor.infocenter.fragments.StorageFragment.java

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private String getExternalFree() {

    long size;/*from w  w  w .  j  av a 2 s . co m*/
    StatFs extStorageStatFs;
    String extStoragePath = getExternalStoragePath();

    if (extStoragePath == null || !(new File(extStoragePath).exists())) {
        return getString(R.string.sto_sub_item_ext_storage_not_available);
    }

    extStorageStatFs = new StatFs(new File(extStoragePath).getAbsolutePath());

    if (mIsApiAtLeast18) {
        size = extStorageStatFs.getAvailableBytes();
    } else {
        size = (long) extStorageStatFs.getAvailableBlocks() * (long) extStorageStatFs.getBlockSize();
    }

    return Utils.getFormattedSize(size);

}

From source file:com.rareventure.gps2.GTG.java

/**
 * If there is a serious problem that would prevent the application from running
 * successfully, this will create an alert and return true.
 * Otherwise if things are good to go, it returns false
 *//*from   w  w  w .j  a v a2 s. c  o m*/
public static boolean checkSdCard(Context context) {
    if (!sdCardMounted(context)) {
        GTG.alert(GTGEvent.ERROR_SDCARD_NOT_MOUNTED);
        return false;
    }

    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    long sdAvailSize = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();

    if (sdAvailSize < MIN_FREE_SPACE_ON_SDCARD) {
        GTG.alert(GTGEvent.ERROR_LOW_FREE_SPACE);
        return false;
    }

    return true;

}

From source file:uk.ac.horizon.ubihelper.service.LogManager.java

public synchronized void logValue(String channelName, JSONObject value) {
    if (!logging) {
        Log.d(TAG, "ignore logValue (not logging) " + channelName + "=" + value);
        return;/*from  w  ww.j  a v  a2s .  c  o  m*/
    }
    Log.d(TAG, "logValue " + channelName + "=" + value);

    // marshall
    long time = System.currentTimeMillis();
    JSONObject lval = new JSONObject();
    byte data[];
    try {
        lval.put("time", time);
        lval.put("name", channelName);
        lval.put("value", value);
        data = lval.toString().getBytes("UTF-8");
    } catch (Exception e) {
        Log.e(TAG, "marshalling log value: " + e);
        return;
    }

    try {
        // quick write?
        if (writeValue(data))
            return;
    } catch (Exception e) {
        Log.w(TAG, "problem writing value: " + e);
    }
    // ensure no open file
    closeCurrentFile();

    // fix up...
    File dir = getLogDirectory(service);
    if (dir == null || !dir.exists() || !dir.canWrite()) {
        signalError("External storage not accessible/present");
        return;
    }
    if (currentLogDir == null && !dir.equals(currentLogDir)) {
        // initialise log dir, i.e. current size
        currentLogDir = dir;
        currentLogDir.mkdirs();
        try {
            cacheFiles = new ArrayList<File>();
            File files[] = currentLogDir.listFiles();
            for (int fi = 0; fi < files.length; fi++)
                cacheFiles.add(files[fi]);
            currentCacheUsage = 0;
            for (File f : cacheFiles)
                currentCacheUsage += f.length();
            Collections.sort(cacheFiles, new Comparator<File>() {
                public int compare(File f1, File f2) {
                    return new Long(f1.lastModified()).compareTo(f2.lastModified());
                }
            });
        } catch (Exception e) {
            signalError("External storage not accessible/present (on check cache size)");
            return;
        }
    }
    // current log configuration
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(service);

    // is there space 
    StatFs fs = new StatFs(currentLogDir.getAbsolutePath());
    long availableFs = fs.getAvailableBlocks() * fs.getBlockSize();
    long availableCache = (maxCacheSize > 0) ? maxCacheSize - currentCacheUsage : availableFs;

    if (availableCache < MIN_NEW_FILE_SIZE) {
        boolean deleteOldFiles = prefs.getBoolean(LOG_DELETE_OLD_FILES, false);
        if (!deleteOldFiles) {
            if (availableCache < availableFs)
                signalError("Log cache full (cannot delete old files)");
            else
                signalError("Log storage device full (cannot delete old files)");
            return;
        }
        // try deleting oldest file first
        while (cacheFiles.size() > 0 && availableCache < MIN_NEW_FILE_SIZE) {
            File f = cacheFiles.remove(0);
            Log.i(TAG, "Deleting old cache file " + f + " (modified "
                    + logDateFormat.format(new Date(f.lastModified())) + ", length " + f.length() + ")");

            long len = f.length();
            currentCacheUsage -= len;
            availableCache += len;
            if (!f.delete()) {
                signalError("Log cache full (failed to delete old file(s))");
                return;
            }
        }
        if (availableCache < MIN_NEW_FILE_SIZE) {
            signalError("Log cache full (no old files)");
            return;
        }
    }

    // new log file
    String filePrefix = prefs.getString(LOG_FILE_PREFIX, "log");

    int i = 1;
    String filename = filePrefix + "_" + logDateFormat.format(new Date(time));
    currentLogFile = new File(currentLogDir, filename + ".log");
    while (currentLogFile.exists()) {
        i++;
        currentLogFile = new File(currentLogDir, filename + "_" + i + ".log");
    }

    try {
        OutputStream os = new FileOutputStream(currentLogFile);
        currentLogStream = new BufferedOutputStream(os, BUFFER_SIZE);
        cacheFiles.add(currentLogFile);
        currentFileLength = 0;
    } catch (Exception e) {
        Log.w(TAG, "Error opening log file " + currentLogFile + ": " + e);
        signalError("Cannot create log file");
        closeCurrentFile();
        return;
    }

    // try again!
    try {
        // quick write?
        if (writeValue(data))
            return;
    } catch (Exception e) {
        Log.w(TAG, "problem writing value: " + e);
    }
    signalError("Cannot write to new log file");
    return;
}