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.example.demo_highlights.slidingmenu.fragment.LeftFragment.java

public void getDataSize() {
    textView2.setText("?");
    progressBar2.setProgress(0);/*from   w w w  .  j  ava 2 s . c  o m*/
    //
    File path = Environment.getDataDirectory();
    //sdcard
    StatFs statfs = new StatFs(path.getPath());
    //blockSIZE
    long blocSize = statfs.getBlockSize();
    //BLOCK
    long totalBlocks = statfs.getBlockCount();
    //Block
    long availaBlock = statfs.getAvailableBlocks();

    String[] total = filesize(totalBlocks * blocSize);
    String[] availale = filesize(availaBlock * blocSize);
    // 
    int maxValue = Integer.parseInt(availale[0].replaceAll(",", "")) * progressBar2.getMax()
            / Integer.parseInt(total[0].replaceAll(",", ""));
    progressBar2.setProgress(100 - maxValue);
    //          String Text="?"+total[0].replaceAll(",", "")+total[1]+"\n"
    //          +"?:"+availale[0].replaceAll(",", "")+availale[1]; 
    String Text = ":"
            + (Integer.parseInt(total[0].replaceAll(",", ""))
                    - Integer.parseInt(availale[0].replaceAll(",", "")))
            + availale[1]/*availale[0].replaceAll(",", "")+availale[1]*/ + " / " + total[0].replaceAll(",", "")
            + total[1];
    textView2.setText(Text);

}

From source file:com.example.demo_highlights.slidingmenu.fragment.LeftFragment.java

public void getSDSize() {
    textView1.setText("");
    progressBar1.setProgress(0);//from w  ww.j  ava 2s. co m
    //
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        File path = Environment.getExternalStorageDirectory();
        //sdcard
        StatFs statfs = new StatFs(path.getPath());
        //blockSIZE
        long blocSize = statfs.getBlockSize();
        //BLOCK
        long totalBlocks = statfs.getBlockCount();
        //Block
        long availaBlock = statfs.getAvailableBlocks();

        String[] total = filesize(totalBlocks * blocSize);
        String[] availale = filesize(availaBlock * blocSize);
        // 
        int maxValue = Integer.parseInt(availale[0].replaceAll(",", "")) * progressBar1.getMax()
                / Integer.parseInt(total[0].replaceAll(",", ""));
        progressBar1.setProgress(100 - maxValue);
        String Text = "SD:"
                + (Integer.parseInt(total[0].replaceAll(",", ""))
                        - Integer.parseInt(availale[0].replaceAll(",", "")))
                + availale[1]/*availale[0].replaceAll(",", "")+availale[1]*/ + " / "
                + total[0].replaceAll(",", "") + total[1];
        textView1.setText(Text);

    } else if (Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)) {
        //          Toast.makeText(getActivity(), "sdCard", 1000).show();
        textView1.setText("SD??");
    }
}

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:com.googlecode.android_scripting.facade.AndroidFacade.java

/**
 * /* ww w.jav a  2s. c  o  m*/
 * 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:org.akvo.flow.activity.SurveyActivity.java

public void spaceLeftOnCard() {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        // TODO: more specific warning if card not mounted?
    }// ww w.ja va 2 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  a v  a 2 s. c  om
                                }
                            }
                        });
                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.att.android.arodatacollector.utils.AROCollectorUtils.java

/**
 * Returns the amount of available memory left on the device SD Card (in
 * bytes)./*  www  .  j a  v  a 2  s .  c  o m*/
 */
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.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. ja v a 2s .c o m
 */

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);
    }

}

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

private void refreshMounts() {
    mMounts.clear();//from  w  ww .  j a va  2 s  .  com

    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();
}