Example usage for android.text.format Formatter formatFileSize

List of usage examples for android.text.format Formatter formatFileSize

Introduction

In this page you can find the example usage for android.text.format Formatter formatFileSize.

Prototype

public static String formatFileSize(@Nullable Context context, long sizeBytes) 

Source Link

Document

Formats a content size to be in the form of bytes, kilobytes, megabytes, etc.

Usage

From source file:com.amaze.carbonfilemanager.services.CopyService.java

/**
 * Publish the results of the progress to notification and {@link DataPackage}
 * and eventually to {@link com.amaze.carbonfilemanager.fragments.ProcessViewer}
 *
 * @param id             id of current service
 * @param fileName       file name of current file being copied
 * @param sourceFiles    total number of files selected by user for copy
 * @param sourceProgress files been copied out of them
 * @param totalSize      total size of selected items to copy
 * @param writtenSize    bytes successfully copied
 * @param speed          number of bytes being copied per sec
 * @param isComplete     whether operation completed or ongoing (not supported at the moment)
 * @param move           if the files are to be moved
 *///from   w w w  .  ja  va2 s  . com
private void publishResults(int id, String fileName, int sourceFiles, int sourceProgress, long totalSize,
        long writtenSize, int speed, boolean isComplete, boolean move) {
    if (!progressHandler.getCancelled()) {

        //notification
        float progressPercent = ((float) writtenSize / totalSize) * 100;
        mBuilder.setProgress(100, Math.round(progressPercent), false);
        mBuilder.setOngoing(true);
        int title = R.string.copying;
        if (move)
            title = R.string.moving;
        mBuilder.setContentTitle(c.getResources().getString(title));
        mBuilder.setContentText(fileName + " " + Formatter.formatFileSize(c, writtenSize) + "/"
                + Formatter.formatFileSize(c, totalSize));
        int id1 = Integer.parseInt("456" + id);
        mNotifyManager.notify(id1, mBuilder.build());
        if (writtenSize == totalSize || totalSize == 0) {
            if (move) {

                //mBuilder.setContentTitle(getString(R.string.move_complete));
                // set progress to indeterminate as deletion might still be going on from source
                mBuilder.setProgress(0, 0, true);
            } else {

                mBuilder.setContentTitle(getString(R.string.copy_complete));
                mBuilder.setProgress(0, 0, false);
            }
            mBuilder.setContentText("");
            mBuilder.setOngoing(false);
            mBuilder.setAutoCancel(true);
            mNotifyManager.notify(id1, mBuilder.build());
            publishCompletedResult(id1);
        }

        //for processviewer
        DataPackage intent = new DataPackage();
        intent.setName(fileName);
        intent.setSourceFiles(sourceFiles);
        intent.setSourceProgress(sourceProgress);
        intent.setTotal(totalSize);
        intent.setByteProgress(writtenSize);
        intent.setSpeedRaw(speed);
        intent.setMove(move);
        intent.setCompleted(isComplete);
        putDataPackage(intent);
        if (progressListener != null) {
            progressListener.onUpdate(intent);
            if (isComplete)
                progressListener.refresh();
        }
    } else
        publishCompletedResult(Integer.parseInt("456" + id));
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

private String[] getMemInfo() {
    Activity ctx = getActivity();//from  w ww.  j  a  v  a  2  s  .c  o m

    long[] state = getMemState(ctx);

    if (state == null) {
        return null;
    }

    String[] mem = new String[state.length];

    for (int i = 0, size = mem.length; i < size; i++) {
        if (state[i] == -1) {
            mem[i] = getString(R.string.info_not_available);
        } else {
            mem[i] = Formatter.formatFileSize(ctx, state[i]);
        }
    }

    return mem;
}

From source file:org.uguess.android.sysinfo.ProcessManager.java

void refreshHeader() {
    if (rootView == null) {
        return;/*ww w  . ja  va 2  s  . c  o  m*/
    }

    Activity ctx = getActivity();

    TextView txt_head_mem = (TextView) rootView.findViewById(R.id.txt_head_mem);
    TextView txt_head_cpu = (TextView) rootView.findViewById(R.id.txt_head_cpu);

    boolean showMem = Util.getBooleanOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SHOW_MEM);
    boolean showCpu = Util.getBooleanOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SHOW_CPU);

    StringBuilder totalString = null;

    if (showMem) {
        txt_head_mem.setVisibility(View.VISIBLE);

        long[] mem = SiragonManager.getMemState(ctx);

        if (mem != null) {
            totalString = new StringBuilder();
            totalString.append(getString(R.string.free)).append(": ") //$NON-NLS-1$
                    .append(Formatter.formatFileSize(ctx, mem[2]));
        }
    } else {
        txt_head_mem.setVisibility(View.GONE);
    }

    if (showCpu) {
        txt_head_cpu.setVisibility(View.VISIBLE);

        long cu = totalDelta == 0 ? 0 : (workDelta * 100 / totalDelta);

        if (cu < 0) {
            cu = 0;
        }
        if (cu > 100) {
            cu = 100;
        }

        if (totalString == null) {
            totalString = new StringBuilder();
            totalString.append(getString(R.string.load)).append(": ") //$NON-NLS-1$
                    .append(cu).append('%');
        } else {
            totalString.append("  ") //$NON-NLS-1$
                    .append(getString(R.string.load)).append(": ") //$NON-NLS-1$
                    .append(cu).append('%');
        }
    } else {
        txt_head_cpu.setVisibility(View.GONE);
    }

    View header = rootView.findViewById(R.id.list_head);

    if (totalString == null) {
        header.setVisibility(View.GONE);
    } else {
        TextView txt_head_total = (TextView) rootView.findViewById(R.id.txt_head_total);
        txt_head_total.setText(totalString);

        header.setVisibility(View.VISIBLE);
    }
}

From source file:org.uguess.android.sysinfo.ProcessManager.java

private static void readProcessStat(Context ctx, byte[] buf, ProcessItem pi, boolean showMem, boolean showCpu) {
    InputStream is = null;// w w  w  .  j  a v a 2 s .  c  om
    try {
        is = new FileInputStream("/proc/" //$NON-NLS-1$
                + pi.procInfo.pid + "/stat"); //$NON-NLS-1$

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        int len;

        while ((len = is.read(buf)) != -1) {
            output.write(buf, 0, len);
        }

        output.close();

        String line = output.toString();

        if (line != null) {
            line = line.trim();

            int idx = line.lastIndexOf(')');

            if (idx != -1) {
                line = line.substring(idx + 1).trim();

                StringTokenizer tokens = new StringTokenizer(line);

                String rss = null;
                String utime = null;
                String stime = null;

                long nrss;
                int i = 0;
                String tk;

                // [11,12,21] for [utime,stime,rss]
                while (tokens.hasMoreTokens()) {
                    tk = tokens.nextToken();

                    if (i == 11) {
                        utime = tk;
                    } else if (i == 12) {
                        stime = tk;
                    } else if (i == 21) {
                        rss = tk;
                    }

                    if (rss != null) {
                        break;
                    }

                    i++;
                }

                if (showCpu) {
                    if (utime != null) {
                        pi.cputime = Long.parseLong(utime);
                    }

                    if (stime != null) {
                        pi.cputime += Long.parseLong(stime);
                    }
                }

                if (showMem && rss != null) {
                    nrss = Long.parseLong(rss);

                    if (pi.rss != nrss || pi.mem == null) {
                        pi.rss = nrss;

                        pi.mem = Formatter.formatFileSize(ctx, pi.rss * 4 * 1024);
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.e(ProcessManager.class.getName(), e.getLocalizedMessage(), e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                Log.e(ProcessManager.class.getName(), e.getLocalizedMessage(), e);
            }
        }
    }
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

/**
 * This checks the built-in app2sd storage info supported since Froyo
 *//*from   ww w.j  a  v  a2s . c o m*/
private String[] getSystemA2SDStorageInfo() {
    Activity ctx = getActivity();
    final PackageManager pm = ctx.getPackageManager();
    List<ApplicationInfo> allApps = pm.getInstalledApplications(0);

    long total = 0;
    long free = 0;

    for (int i = 0, size = allApps.size(); i < size; i++) {
        ApplicationInfo info = allApps.get(i);

        if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
            String src = info.sourceDir;

            if (src != null) {
                File srcFile = new File(src);

                if (srcFile.canRead()) {
                    try {
                        StatFs stat = new StatFs(srcFile.getAbsolutePath());
                        long blockSize = stat.getBlockSize();

                        total += stat.getBlockCount() * blockSize;
                        free += stat.getAvailableBlocks() * blockSize;
                    } catch (Exception e) {
                        Log.e(SiragonManager.class.getName(), "Cannot access path: " //$NON-NLS-1$
                                + srcFile.getAbsolutePath(), e);
                    }
                }
            }
        }
    }

    if (total > 0) {
        String[] info = new String[2];
        info[0] = Formatter.formatFileSize(ctx, total);
        info[1] = Formatter.formatFileSize(ctx, free);

        return info;
    }

    return null;
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

private String[] getStorageInfo(File path) {
    if (path != null) {
        try {/*from  www. j  a v  a 2  s. c  o  m*/
            Activity ctx = getActivity();

            StatFs stat = new StatFs(path.getAbsolutePath());
            long blockSize = stat.getBlockSize();

            String[] info = new String[2];
            info[0] = Formatter.formatFileSize(ctx, stat.getBlockCount() * blockSize);
            info[1] = Formatter.formatFileSize(ctx, stat.getAvailableBlocks() * blockSize);

            return info;
        } catch (Exception e) {
            Log.e(SiragonManager.class.getName(), "Cannot access path: " //$NON-NLS-1$
                    + path.getAbsolutePath(), e);
        }
    }

    return null;
}

From source file:org.uguess.android.sysinfo.ApplicationManager.java

void handleAction(final AppInfoHolder ai, int action) {
    Activity ctx = getActivity();/*from   w  w w.ja v a2 s.co m*/
    String pkgName = ai.appInfo.packageName;

    switch (action) {
    case ACTION_MENU:

        OnClickListener listener = new OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                // bypass the 'showMenu' action offset
                int action = which + 1;

                handleAction(ai, action);
            }
        };

        new AlertDialog.Builder(ctx).setTitle(R.string.actions)
                .setItems(new CharSequence[] { getString(R.string.manage), getString(R.string.run),
                        getString(R.string.search_market), getString(R.string.details) }, listener)
                .create().show();

        break;
    case ACTION_MANAGE:

        Intent it = new Intent(Intent.ACTION_VIEW);

        it.setClassName("com.android.settings", //$NON-NLS-1$
                "com.android.settings.InstalledAppDetails"); //$NON-NLS-1$
        it.putExtra("com.android.settings.ApplicationPkgName", pkgName); //$NON-NLS-1$
        // this is for Froyo
        it.putExtra("pkg", pkgName); //$NON-NLS-1$

        List<ResolveInfo> acts = ctx.getPackageManager().queryIntentActivities(it, 0);

        if (acts.size() > 0) {
            startActivity(it);
        } else {
            // for ginger bread
            it = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", //$NON-NLS-1$
                    Uri.fromParts("package", pkgName, null)); //$NON-NLS-1$

            acts = ctx.getPackageManager().queryIntentActivities(it, 0);

            if (acts.size() > 0) {
                startActivity(it);
            } else {
                Log.d(ApplicationManager.class.getName(), "Failed to resolve activity for InstalledAppDetails"); //$NON-NLS-1$
            }
        }

        break;
    case ACTION_LAUNCH:

        if (!pkgName.equals(ctx.getPackageName())) {
            it = new Intent("android.intent.action.MAIN"); //$NON-NLS-1$
            it.addCategory(Intent.CATEGORY_LAUNCHER);

            acts = ctx.getPackageManager().queryIntentActivities(it, 0);

            if (acts != null) {
                boolean started = false;

                for (int i = 0, size = acts.size(); i < size; i++) {
                    ResolveInfo ri = acts.get(i);

                    if (pkgName.equals(ri.activityInfo.packageName)) {
                        it.setClassName(ri.activityInfo.packageName, ri.activityInfo.name);

                        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        try {
                            startActivity(it);

                            started = true;

                        } catch (Exception e) {
                            Log.e(ApplicationManager.class.getName(), "Cannot start activity: " + pkgName, //$NON-NLS-1$
                                    e);
                        }

                        break;
                    }
                }

                if (!started) {
                    Util.shortToast(ctx, R.string.run_failed);
                }
            }
        }

        break;
    case ACTION_SEARCH:

        it = new Intent(Intent.ACTION_VIEW);

        it.setData(Uri.parse("market://search?q=pname:" + pkgName)); //$NON-NLS-1$

        it = Intent.createChooser(it, null);

        startActivity(it);

        break;
    case ACTION_DETAILS:

        ApplicationInfo appInfo = ai.appInfo;

        String installDate;
        String fileSize;

        if (appInfo.sourceDir != null) {
            File f = new File(appInfo.sourceDir);
            installDate = DateUtils.formatDateTime(ctx, f.lastModified(),
                    DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
            fileSize = Formatter.formatFileSize(ctx, f.length());
        } else {
            installDate = fileSize = getString(R.string.unknown);
        }

        StringBuffer sb = new StringBuffer().append("<small>") //$NON-NLS-1$
                .append(getString(R.string.pkg_name)).append(": ") //$NON-NLS-1$
                .append(appInfo.packageName).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.version_code)).append(": ") //$NON-NLS-1$
                .append(ai.versionCode).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.target_sdk)).append(": ") //$NON-NLS-1$
                .append(Util.getTargetSdkVersion(ctx, appInfo)).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.uid)).append(": ") //$NON-NLS-1$
                .append(appInfo.uid).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.file_size)).append(": ") //$NON-NLS-1$
                .append(fileSize).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.public_source)).append(": ") //$NON-NLS-1$
                .append(appInfo.publicSourceDir).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.source)).append(": ") //$NON-NLS-1$
                .append(appInfo.sourceDir).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.data)).append(": ") //$NON-NLS-1$
                .append(appInfo.dataDir).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.installed_date)).append(": ") //$NON-NLS-1$
                .append(installDate).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.process)).append(": ") //$NON-NLS-1$
                .append(appInfo.processName).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.app_class)).append(": ") //$NON-NLS-1$
                .append(appInfo.className == null ? "" //$NON-NLS-1$
                        : appInfo.className)
                .append("<br>") //$NON-NLS-1$
                .append(getString(R.string.task_affinity)).append(": ") //$NON-NLS-1$
                .append(appInfo.taskAffinity).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.permission)).append(": ") //$NON-NLS-1$
                .append(appInfo.permission == null ? "" //$NON-NLS-1$
                        : appInfo.permission)
                .append("<br>") //$NON-NLS-1$
                .append(getString(R.string.flags)).append(": ") //$NON-NLS-1$
                .append(appInfo.flags).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.enabled)).append(": ") //$NON-NLS-1$
                .append(appInfo.enabled).append("<br>") //$NON-NLS-1$
                .append(getString(R.string.manage_space_ac)).append(": ") //$NON-NLS-1$
                .append(appInfo.manageSpaceActivityName == null ? "" //$NON-NLS-1$
                        : appInfo.manageSpaceActivityName)
                .append("</small>"); //$NON-NLS-1$

        new AlertDialog.Builder(ctx).setTitle(ai.label == null ? appInfo.packageName : ai.label)
                .setNeutralButton(R.string.close, null).setMessage(Html.fromHtml(sb.toString())).create()
                .show();

        break;
    }
}

From source file:org.proninyaroslav.libretorrent.services.TorrentTaskService.java

private NotificationCompat.InboxStyle makeDetailNotifyInboxStyle() {
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    String titleTemplate = getString(R.string.torrent_count_notify_template);

    int downloadingCount = 0;

    for (TorrentDownload task : torrentTasks.values()) {
        if (task == null) {
            continue;
        }//from w  ww  . j  a  v a 2 s  . c  o m

        String template;
        TorrentStateCode code = task.getStateCode();

        if (code == TorrentStateCode.DOWNLOADING) {
            ++downloadingCount;
            template = getString(R.string.downloading_torrent_notify_template);
            inboxStyle.addLine(String.format(template, task.getProgress(),
                    (task.getETA() == -1) ? Utils.INFINITY_SYMBOL : DateUtils.formatElapsedTime(task.getETA()),
                    Formatter.formatFileSize(this, task.getDownloadSpeed()), task.getTorrent().getName()));

        } else if (code == TorrentStateCode.SEEDING) {
            template = getString(R.string.seeding_torrent_notify_template);
            inboxStyle.addLine(String.format(template, getString(R.string.torrent_status_seeding),
                    Formatter.formatFileSize(this, task.getUploadSpeed()), task.getTorrent().getName()));
        } else {
            String stateString = "";

            switch (task.getStateCode()) {
            case PAUSED:
                stateString = getString(R.string.torrent_status_paused);
                break;
            case STOPPED:
                stateString = getString(R.string.torrent_status_stopped);
                break;
            case CHECKING:
                stateString = getString(R.string.torrent_status_checking);
                break;
            }

            template = getString(R.string.other_torrent_notify_template);
            inboxStyle.addLine(String.format(template, stateString, task.getTorrent().getName()));
        }
    }

    inboxStyle.setBigContentTitle(String.format(titleTemplate, downloadingCount, torrentTasks.size()));

    inboxStyle.setSummaryText(
            (isNetworkOnline ? getString(R.string.network_online) : getString(R.string.network_offline)));

    return inboxStyle;
}

From source file:com.amaze.filemanager.fragments.MainFragment.java

public ArrayList<LayoutElementParcelable> addToSmb(SmbFile[] mFile, String path, boolean showHiddenFiles)
        throws SmbException {
    ArrayList<LayoutElementParcelable> smbFileList = new ArrayList<>();
    if (searchHelper.size() > 500)
        searchHelper.clear();/*  ww w . j  ava 2s  .  co m*/
    for (SmbFile aMFile : mFile) {
        if ((dataUtils.isFileHidden(aMFile.getPath()) || aMFile.isHidden()) && !showHiddenFiles) {
            continue;
        }
        String name = aMFile.getName();
        name = (aMFile.isDirectory() && name.endsWith("/")) ? name.substring(0, name.length() - 1) : name;
        if (path.equals(smbPath)) {
            if (name.endsWith("$"))
                continue;
        }
        if (aMFile.isDirectory()) {
            folder_count++;

            LayoutElementParcelable layoutElement = new LayoutElementParcelable(name, aMFile.getPath(), "", "",
                    "", 0, false, aMFile.lastModified() + "", true, getBoolean(PREFERENCE_SHOW_THUMB),
                    OpenMode.SMB);

            searchHelper.add(layoutElement.generateBaseFile());
            smbFileList.add(layoutElement);

        } else {
            file_count++;
            LayoutElementParcelable layoutElement = new LayoutElementParcelable(name, aMFile.getPath(), "", "",
                    Formatter.formatFileSize(getContext(), aMFile.length()), aMFile.length(), false,
                    aMFile.lastModified() + "", false, getBoolean(PREFERENCE_SHOW_THUMB), OpenMode.SMB);
            layoutElement.setMode(OpenMode.SMB);
            searchHelper.add(layoutElement.generateBaseFile());
            smbFileList.add(layoutElement);
        }
    }
    return smbFileList;
}

From source file:com.amaze.filemanager.fragments.MainFragment.java

private LayoutElementParcelable addTo(HybridFileParcelable mFile) {
    File f = new File(mFile.getPath());
    String size = "";
    if (!dataUtils.isFileHidden(mFile.getPath())) {
        if (mFile.isDirectory()) {
            size = "";
            LayoutElementParcelable layoutElement = new LayoutElementParcelable(f.getPath(),
                    mFile.getPermission(), mFile.getLink(), size, 0, true, mFile.getDate() + "", false,
                    getBoolean(PREFERENCE_SHOW_THUMB), mFile.getMode());

            LIST_ELEMENTS.add(layoutElement);
            folder_count++;//from  w w  w .j a  v  a 2  s.  c  om
            return layoutElement;
        } else {
            long longSize = 0;
            try {
                if (mFile.getSize() != -1) {
                    longSize = mFile.getSize();
                    size = Formatter.formatFileSize(getContext(), longSize);
                } else {
                    size = "";
                    longSize = 0;
                }
            } catch (NumberFormatException e) {
                //e.printStackTrace();
            }
            try {
                LayoutElementParcelable layoutElement = new LayoutElementParcelable(f.getPath(),
                        mFile.getPermission(), mFile.getLink(), size, longSize, false, mFile.getDate() + "",
                        false, getBoolean(PREFERENCE_SHOW_THUMB), mFile.getMode());
                LIST_ELEMENTS.add(layoutElement);
                file_count++;
                return layoutElement;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}