Example usage for android.os StatFs getBlockSize

List of usage examples for android.os StatFs getBlockSize

Introduction

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

Prototype

@Deprecated
public int getBlockSize() 

Source Link

Usage

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
 *//*w w w . ja v a  2  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;//  w w  w  .  java2 s  .com
    }
    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;
}

From source file:org.wso2.emm.system.service.api.OTAServerManager.java

public long getFreeDiskSpace() {
    StatFs statFs = new StatFs(FileUtils.getUpgradePackageDirectory());
    long freeDiskSpace = (long) statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
    Log.d(TAG, "Free disk space: " + freeDiskSpace);
    return freeDiskSpace;
}

From source file:org.akvo.flow.activity.SurveyActivity.java

public void spaceLeftOnCard() {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        // TODO: more specific warning if card not mounted?
    }/*w w w . ja va2 s  .  c o  m*/
    // compute space left
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize();
    // One binary gigabyte equals 1,073,741,824 bytes.
    // double gigaAvailable = sdAvailSize / 1073741824;
    // One binary megabyte equals 1 048 576 bytes.
    long megaAvailable = (long) Math.floor(sdAvailSize / 1048576.0);

    // keep track of changes
    SharedPreferences settings = getPreferences(MODE_PRIVATE);
    // assume we had space before
    long lastMegaAvailable = settings.getLong("cardMBAvaliable", 101L);
    SharedPreferences.Editor editor = settings.edit();
    editor.putLong("cardMBAvaliable", megaAvailable);
    // Commit the edits!
    editor.commit();

    if (megaAvailable <= 0L) {// All out, OR media not mounted
        // Bounce user
        ViewUtil.showConfirmDialog(R.string.nocardspacetitle, R.string.nocardspacedialog, this, false,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        finish();
                    }
                });
        return;
    }

    // just issue a warning if we just descended to or past a number on the list
    if (megaAvailable < lastMegaAvailable) {
        for (long l = megaAvailable; l < lastMegaAvailable; l++) {
            if (ConstantUtil.SPACE_WARNING_MB_LEVELS.contains(Long.toString(l))) {
                // display how much space is left
                String s = getResources().getString(R.string.lowcardspacedialog);
                s = s.replace("%%%", Long.toString(megaAvailable));
                ViewUtil.showConfirmDialog(R.string.lowcardspacetitle, s, this, false,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                            }
                        }, null);
                return; // only one warning per survey, even of we passed >1 limit
            }
        }
    }
}

From source file:org.kde.necessitas.ministro.MinistroActivity.java

private boolean checkFreeSpace(final long size) throws InterruptedException {
    final StatFs stat = new StatFs(m_qtLibsRootPath);
    if (stat.getBlockSize() * stat.getAvailableBlocks() < size) {
        runOnUiThread(new Runnable() {
            public void run() {

                AlertDialog.Builder builder = new AlertDialog.Builder(MinistroActivity.this);
                builder.setMessage(getResources().getString(R.string.ministro_disk_space_msg,
                        (size - (stat.getBlockSize() * stat.getAvailableBlocks())) / 1024 + "Kb"));
                builder.setCancelable(true);
                builder.setNeutralButton(getResources().getString(R.string.settings_msg),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                try {
                                    startActivityForResult(
                                            new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS),
                                            freeSpaceCode);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    try {
                                        startActivityForResult(
                                                new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS),
                                                freeSpaceCode);
                                    } catch (Exception e1) {

                                        e1.printStackTrace();
                                    }//ww  w.j av a2s  . c  o m
                                }
                            }
                        });
                builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                        m_diskSpaceSemaphore.release();
                    }
                });
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    public void onCancel(DialogInterface dialog) {
                        dialog.dismiss();
                        m_diskSpaceSemaphore.release();
                    }
                });
                m_distSpaceDialog = builder.create();
                m_distSpaceDialog.show();
            }
        });
        m_diskSpaceSemaphore.acquire();
    } else
        return true;

    return stat.getBlockSize() * stat.getAvailableBlocks() > size;
}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

/**
 * /*www.ja va2  s. com*/
 * Map returned:
 * 
 * <pre>
 *   TZ = Timezone
 *     id = Timezone ID
 *     display = Timezone display name
 *     offset = Offset from UTC (in ms)
 *   SDK = SDK Version
 *   download = default download path
 *   appcache = Location of application cache 
 *   sdcard = Space on sdcard
 *     availblocks = Available blocks
 *     blockcount = Total Blocks
 *     blocksize = size of block.
 * </pre>
 */
@Rpc(description = "A map of various useful environment details")
public Map<String, Object> environment() {
    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, Object> zone = new HashMap<String, Object>();
    Map<String, Object> space = new HashMap<String, Object>();
    TimeZone tz = TimeZone.getDefault();
    zone.put("id", tz.getID());
    zone.put("display", tz.getDisplayName());
    zone.put("offset", tz.getOffset((new Date()).getTime()));
    result.put("TZ", zone);
    result.put("SDK", android.os.Build.VERSION.SDK);
    result.put("download", FileUtils.getExternalDownload().getAbsolutePath());
    result.put("appcache", mService.getCacheDir().getAbsolutePath());
    try {
        StatFs fs = new StatFs("/sdcard");
        space.put("availblocks", fs.getAvailableBlocks());
        space.put("blocksize", fs.getBlockSize());
        space.put("blockcount", fs.getBlockCount());
    } catch (Exception e) {
        space.put("exception", e.toString());
    }
    result.put("sdcard", space);
    return result;
}

From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java

/**
 * Returns the amount of available memory left on the device SD Card (in
 * bytes).//  w  w  w . j a va2 s . c om
 */
public long checkSDCardMemoryAvailable() {
    final StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    final long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
    final long kbsAvailable = bytesAvailable / 1024;
    // float megAvailable = (long) (bytesAvailable / (1024.f * 1024.f));
    return kbsAvailable;
}

From source file:com.github.chenxiaolong.dualbootpatcher.freespace.FreeSpaceFragment.java

private void refreshMounts() {
    mMounts.clear();/*w w w. j a  v a2 s .  c  o  m*/

    MountEntry[] entries;

    try {
        entries = FileUtils.getMounts();
    } catch (IOException e) {
        Log.e(TAG, "Failed to get mount entries", e);
        return;
    }

    for (MountEntry entry : entries) {
        MountInfo info = new MountInfo();
        info.mountpoint = entry.mnt_dir;
        info.fsname = entry.mnt_fsname;
        info.fstype = entry.mnt_type;

        // Ignore irrelevant filesystems
        if (SKIPPED_FSTYPES.contains(info.fstype) || SKIPPED_FSNAMES.contains(info.fsname)
                || info.mountpoint.startsWith("/mnt") || info.mountpoint.startsWith("/dev")
                || info.mountpoint.startsWith("/proc") || info.mountpoint.startsWith("/data/data")) {
            continue;
        }

        StatFs statFs;

        try {
            statFs = new StatFs(info.mountpoint);
        } catch (IllegalArgumentException e) {
            // Thrown if Os.statvfs() throws ErrnoException
            Log.e(TAG, "Exception during statfs of " + info.mountpoint + ": " + e.getMessage());
            continue;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            info.totalSpace = statFs.getBlockSizeLong() * statFs.getBlockCountLong();
            info.availSpace = statFs.getBlockSizeLong() * statFs.getAvailableBlocksLong();
        } else {
            info.totalSpace = statFs.getBlockSize() * statFs.getBlockCount();
            info.availSpace = statFs.getBlockSize() * statFs.getAvailableBlocks();
        }

        mMounts.add(info);
    }

    mAdapter.notifyDataSetChanged();
}

From source file:com.p2p.misc.DeviceUtility.java

public String[] memCardDetails() {

    String[] memDetails = new String[3];

    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize();
    double sdtotalSize = (double) stat.getBlockCount() * (double) stat.getBlockSize();
    // One binary gigabyte equals 1,073,741,824 bytes.
    float gigaTotal = (float) (sdtotalSize / 1073741824);
    float gigaAvailable = (float) (sdAvailSize / 1073741824);
    float usedSize = gigaTotal - gigaAvailable;
    memDetails[0] = String.valueOf(gigaTotal);
    memDetails[1] = String.valueOf(gigaAvailable);
    memDetails[2] = String.valueOf(usedSize);

    return memDetails;
}

From source file:cz.muni.fi.japanesedictionary.parser.ParserService.java

/**
 * Downloads dictionaries.//  w ww.j  av a2 s. c  om
 */

protected void onHandleIntent() {

    Log.i(LOG_TAG, "Creating parser service");

    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this).setAutoCancel(false).setOngoing(true)
            .setContentTitle(getString(R.string.dictionary_download_title))
            .setContentText(getString(R.string.dictionary_download_in_progress) + " (1/5)")
            .setSmallIcon(R.drawable.ic_notification).setProgress(100, 0, false).setContentInfo("0%")
            .setContentIntent(resultPendingIntent);

    startForeground(0, mNotification);
    mNotifyManager.notify(0, mBuilder.build());
    File storage;
    if (MainActivity.canWriteExternalStorage()) {
        // external storage available
        storage = getExternalCacheDir();
    } else {
        storage = getCacheDir();
    }
    if (storage == null) {
        throw new IllegalStateException("External storage isn't accessible");
    }
    // free sapce controll
    StatFs stat = new StatFs(storage.getPath());
    long bytesAvailable;
    if (Build.VERSION.SDK_INT < 18) {
        bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
    } else {
        bytesAvailable = stat.getAvailableBytes();
    }
    long megAvailable = bytesAvailable / 1048576;
    Log.d(LOG_TAG, "Megs free :" + megAvailable);
    if (megAvailable < 140) {
        mInternetReceiver = null;
        mNotEnoughSpace = true;
        stopSelf(mStartId);
        return;
    }

    this.registerReceiver(mInternetReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean english = sharedPrefs.getBoolean("language_english", false);
    boolean french = sharedPrefs.getBoolean("language_french", false);
    boolean dutch = sharedPrefs.getBoolean("language_dutch", false);
    boolean german = sharedPrefs.getBoolean("language_german", false);
    boolean russian = sharedPrefs.getBoolean("language_russian", false);
    if (!english && !french && !dutch && !german && !russian) {
        Log.i(LOG_TAG, "Setting english as only translation language");
        SharedPreferences.Editor editor_lang = sharedPrefs.edit();
        editor_lang.putBoolean("language_english", true);
        editor_lang.commit();
    }

    String dictionaryPath;
    String kanjiDictPath;

    URL url;
    try {
        url = new URL(ParserService.DICTIONARY_PATH);
    } catch (MalformedURLException ex) {
        Log.e(LOG_TAG, "Error: creating url for downloading dictionary");
        return;
    }

    try {

        dictionaryPath = storage.getPath() + File.separator + "dictionary.zip";
        File outputFile = new File(dictionaryPath);
        if (outputFile.exists()) {
            outputFile.delete();
        }

        mDownloadJMDictFrom = url;
        mDownloadJMDictTo = outputFile;
        mDownloadingJMDict = true;
        mDownloadInProgress = true;

        // downloading kanjidict
        url = null;
        try {
            url = new URL(ParserService.KANJIDICT_PATH);
        } catch (MalformedURLException ex) {
            Log.e(LOG_TAG, "Error: creating url for downloading kanjidict2");
        }
        if (url != null) {
            kanjiDictPath = storage.getPath() + File.separator + "kanjidict.zip";
            File fileKanjidict = new File(kanjiDictPath);
            if (fileKanjidict.exists()) {
                fileKanjidict.delete();
            }
            mDownloadingKanjidic = false;
            mDownloadKanjidicFrom = url;
            mDownloadKanjidicTo = fileKanjidict;
        }

        mDownloadTatoebaIndicesFrom = new URL(ParserService.TATOEBA_INDICES_PATH);
        mDownloadTatoebaIndicesTo = new File(storage, "tatoeba-japanese.zip");
        if (mDownloadTatoebaIndicesTo.exists()) {
            mDownloadTatoebaIndicesTo.delete();
        }

        mDownloadTatoebaSentencesFrom = new URL(ParserService.TATOEBA_SENTENCES_PATH);
        mDownloadTatoebaSentencesTo = new File(storage, "tatoeba-translation.zip");
        if (mDownloadTatoebaSentencesTo.exists()) {
            mDownloadTatoebaSentencesTo.delete();
        }

        mDownloadKanjiVGFrom = new URL(ParserService.KANJIVG_PATH);
        mDownloadKanjiVGTo = new File(storage, "kanjivg.zip");
        if (mDownloadKanjiVGTo.exists()) {
            mDownloadKanjiVGTo.delete();
        }

        downloadDictionaries();

    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "MalformedURLException wrong format of URL: " + e.toString());
        stopSelf(mStartId);
    } catch (IOException e) {
        Log.e(LOG_TAG, "IOException downloading interrupted: " + e.toString());
        stopSelf(mStartId);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(LOG_TAG, "Exception: " + e.toString());
        stopSelf(mStartId);
    }

}