下面列出了怎么用android.text.format.Formatter的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();
if (id == R.id.vm_preview_origin_cb) {
if (isChecked) {
long size = 0;
for (VMPictureBean item : mSelectedPictures) {
size += item.size;
}
String fileSize = Formatter.formatFileSize(this, size);
isOrigin = true;
mOriginCB.setText(getString(R.string.vm_pick_origin_size, fileSize));
} else {
isOrigin = false;
mOriginCB.setText(getString(R.string.vm_pick_origin));
}
}
}
/**
* 初始化图片选择回调
* 图片添加成功后,修改当前图片的选中数量
*/
private void initSelectedPictureListener() {
mSelectedPictureListener = (position, item, isAdd) -> {
if (VMPicker.getInstance().getSelectPictureCount() > 0) {
int selectCount = VMPicker.getInstance().getSelectPictureCount();
int selectLimit = VMPicker.getInstance().getSelectLimit();
String complete = VMStr.byResArgs(R.string.vm_pick_complete_select, selectCount, selectLimit);
getTopBar().setEndBtn(complete);
} else {
getTopBar().setEndBtn(VMStr.byRes(R.string.vm_pick_complete));
}
if (mOriginCB.isChecked()) {
long size = 0;
for (VMPictureBean VMPictureBean : mSelectedPictures) {
size += VMPictureBean.size;
}
String fileSize = Formatter.formatFileSize(mActivity, size);
mOriginCB.setText(getString(R.string.vm_pick_origin_size, fileSize));
}
};
VMPicker.getInstance().addOnSelectedPictureListener(mSelectedPictureListener);
mSelectedPictureListener.onPictureSelected(0, null, false);
}
/**
* 调用此方法自动计算指定文件或指定文件夹的大小
*
* @param filePath 文件路径
* @return 计算好的带B、KB、MB、GB的字符串
*/
public static String getAutoFileOrFilesSize(String filePath) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
}
else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
PLog.e("获取文件大小失败!");
}
return Formatter.formatFileSize(BaseApplication.getAppContext(),blockSize);
}
public void updateDownloadProgress(View view, Layer layer) {
int progress = downloadManager.getProgress(layer);
long size = layer.getFileSize();
final ProgressBar progressBar = view.findViewById(R.id.layer_progress);
final View download = view.findViewById(R.id.layer_download);
if (progress <= 0) {
String reason = downloadManager.isFailed(layer);
if(!StringUtils.isEmpty(reason)) {
Toast.makeText(context, reason, Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
download.setVisibility(View.VISIBLE);
}
return;
}
int currentProgress = (int) (progress / (float) size * 100);
progressBar.setIndeterminate(false);
progressBar.setProgress(currentProgress);
TextView layerSize = view.findViewById(R.id.layer_size);
layerSize.setText(String.format("Downloading: %s of %s",
Formatter.formatFileSize(context, progress),
Formatter.formatFileSize(context, size)));
}
/**
* 获取 CPU 最大频率 ( 单位 KHZ)
* @return CPU 最大频率 ( 单位 KHZ)
*/
public static String getMaxCpuFreq() {
String result = "";
ProcessBuilder cmd;
InputStream is = null;
try {
String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
cmd = new ProcessBuilder(args);
Process process = cmd.start();
is = process.getInputStream();
byte[] re = new byte[24];
while (is.read(re) != -1) {
result = result + new String(re);
}
result = Formatter.formatFileSize(DevUtils.getContext(), Long.parseLong(result.trim()) * 1024) + " Hz";
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getMaxCpuFreq");
result = "unknown";
} finally {
CloseUtils.closeIOQuietly(is);
}
return result;
}
private void update(long usedBytes) {
Context context = mSpaceUsedTextView.getContext();
if (mFileSystemBytes == Long.MAX_VALUE) {
try {
mFileSystemBytes = mFileSystemBytesTask.get();
} catch (Exception e) {
Log.e(TAG, "Failed to get file system size.");
}
// Display how big the storage is.
String fileSystemReadable = Formatter.formatFileSize(context, mFileSystemBytes);
mSpaceTotalTextView.setText(context.getString(
R.string.download_manager_ui_space_used, fileSystemReadable));
}
// Indicate how much space has been used by downloads.
int percentage =
mFileSystemBytes == 0 ? 0 : (int) (100.0 * usedBytes / mFileSystemBytes);
mSpaceBar.setProgress(percentage);
mSpaceUsedTextView.setText(Formatter.formatFileSize(context, usedBytes));
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();
if (id == R.id.cb_origin) {
if (isChecked) {
long size = 0;
for (ImageItem item : selectedImages)
size += item.size;
String fileSize = Formatter.formatFileSize(this, size);
isOrigin = true;
mCbOrigin.setText(getString(R.string.origin_size, fileSize));
} else {
isOrigin = false;
mCbOrigin.setText("原图");
}
}
}
/**
* init data
*/
@Override
protected void initData() {
long totalRxBytes = TrafficStats.getTotalRxBytes();
long totalTxBytes = TrafficStats.getTotalTxBytes();
long mobileRxBytes = TrafficStats.getMobileRxBytes();
long mobileTxBytes = TrafficStats.getMobileTxBytes();
long totalBytes = totalRxBytes + totalTxBytes;
long mobileBytes = mobileRxBytes + mobileTxBytes;
tvTotalTrafficStatsSum.setText(getString(R.string.total_traffic_stats_sum, Formatter.formatFileSize(this, totalBytes)));
tvMobileTrafficStatsSum.setText(getString(R.string.mobile_traffic_stats_sum, Formatter.formatFileSize(this, mobileBytes)));
tvTotalTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, totalTxBytes), Formatter.formatFileSize(this, totalRxBytes)));
tvMobileTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, mobileTxBytes), Formatter.formatFileSize(this, mobileRxBytes)));
}
@Override
protected Pair<String, List<PieEntry>> doInBackground(Void... params) {
long[] dataArray = Futils.getSpaces(file, context, new OnProgressUpdate<Long[]>() {
@Override
public void onUpdate(Long[] data) {
publishProgress(data);
}
});
if (dataArray != null && dataArray[0] != -1 && dataArray[0] != 0) {
long totalSpace = dataArray[0];
List<PieEntry> entries = createEntriesFromArray(dataArray, false);
return new Pair<String, List<PieEntry>>(Formatter.formatFileSize(context, totalSpace), entries);
}
return null;
}
@Override
public synchronized void trimMemory(int level) {
if (closed) {
return;
}
long memoryCacheSize = getSize();
if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
cache.evictAll();
} else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) {
cache.trimToSize(cache.maxSize() / 2);
}
long releasedSize = memoryCacheSize - getSize();
SLog.w(NAME, "trimMemory. level=%s, released: %s",
SketchUtils.getTrimLevelName(level), Formatter.formatFileSize(context, releasedSize));
}
@Override
public synchronized SketchRefBitmap remove(@NonNull String key) {
if (closed) {
return null;
}
if (disabled) {
if (SLog.isLoggable(SLog.LEVEL_DEBUG | SLog.TYPE_CACHE)) {
SLog.d(NAME, "Disabled. Unable remove, key=%s", key);
}
return null;
}
SketchRefBitmap refBitmap = cache.remove(key);
if (SLog.isLoggable(SLog.LEVEL_DEBUG | SLog.TYPE_CACHE)) {
SLog.d(NAME, "remove. memoryCacheSize: %s",
Formatter.formatFileSize(context, cache.size()));
}
return refBitmap;
}
@Override
protected void onPostExecute(List<ZipEntry> result) {
dataSourceL1.addAll(result);
selectedInList1.clear();
srcAdapter.notifyDataSetChanged();
selectionStatusTV.setText(selectedInList1.size()
+ "/" + dataSourceL1.size());
rightStatus.setText(
Formatter.formatFileSize(activity, zip.file.length())
+ "/" + Formatter.formatFileSize(activity, zip.unZipSize));
if (dataSourceL1.size() == 0) {
nofilelayout.setVisibility(View.VISIBLE);
} else {
nofilelayout.setVisibility(View.GONE);
}
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void run() {
long downloadSpeedValue = DownloadManager.getDownloadSpeed();
String downloadSpeedText = "Speed:" + Formatter.formatShortFileSize(getActivity(),
downloadSpeedValue) + "/s";
downloadSpeed.setText(downloadSpeedText);
if (downloadSpeedValue > 0) {
long remainingMills = DownloadManager.getRemaining();
String remainingText = "Remaining:" + Utils.getHrsMinsSecs(remainingMills);
remaining.setText(remainingText);
} else {
remaining.setText(R.string.remaining_undefine);
}
if (getFragmentManager() != null && getFragmentManager().findFragmentByTag
("downloadsInProgress") != null) {
downloadsInProgress.updateDownloadItem();
}
mainHandler.postDelayed(this, 1000);
}
public static String getRamInfo(Context context) {
long totalSize;
long availableSize;
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
totalSize = memoryInfo.totalMem;
availableSize = memoryInfo.availMem;
return String.format("%s / %s", Formatter.formatFileSize(context, availableSize), Formatter.formatFileSize(context, totalSize));
}
@Override
public void onDownloadStarted(@NonNull Video video, long estimatedSize, @NonNull Map<String, Serializable> mediaProperties) {
videoListAdapter.notifyVideoChanged(video);
String message = showToast(
"Started to download '%s' video. Estimated = %s, width = %s, height = %s, mimeType = %s",
video.getName(),
Formatter.formatFileSize(MainActivity.this, estimatedSize),
mediaProperties.get(Event.RENDITION_WIDTH),
mediaProperties.get(Event.RENDITION_HEIGHT),
mediaProperties.get(Event.RENDITION_MIME_TYPE)
);
Log.i(TAG, message);
}
public void setProgressOfWriteBytes(long current,long total){
if(current<0)return;
if(current>total)return;
progressBar.setMax((int)(total/1024));
progressBar.setProgress((int)(current/1024));
DecimalFormat dm=new DecimalFormat("#.00");
int percent=(int)(Double.valueOf(dm.format((double)current/total))*100);
att_right.setText(Formatter.formatFileSize(getContext(),current)+"/"+Formatter.formatFileSize(getContext(),total)+"("+percent+"%)");
}
@Override
public void onBindViewHolder(ItemArray itemArray, AppViewHolder vh, int position) {
App app = itemArray.get(position).getData();
Context context = vh.itemView.getContext().getApplicationContext();
vh.mApp = app;
vh.getIcon();
vh.mNameTV.setText(app.name);
int colorDagger = ContextCompat.getColor(context, R.color.red500);
int colorNor = ContextCompat.getColor(context, R.color.blue500);
if (app.isSystem) {
vh.mSystemTV.setTextColor(colorDagger);
vh.mSystemTV.setText(R.string.system);
} else {
vh.mSystemTV.setTextColor(colorNor);
vh.mSystemTV.setText(R.string.third_party);
}
if (app.isDebug) {
vh.mDebugTV.setTextColor(colorNor);
vh.mDebugTV.setText(R.string.debug);
} else {
vh.mDebugTV.setTextColor(colorDagger);
vh.mDebugTV.setText(R.string.release);
}
vh.mSizeTV.setText(Formatter.formatFileSize(context, new File(app.apkPath).length()));
vh.mVersionNameTV.setText(app.versionName);
vh.mTimeTV.setText(app.time);
}
public static String getRamInfo(Context context) {
long totalSize;
long availableSize;
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
totalSize = memoryInfo.totalMem;
availableSize = memoryInfo.availMem;
return String.format("%s / %s", Formatter.formatFileSize(context, availableSize), Formatter.formatFileSize(context, totalSize));
}
public void setFileSize(WFile file) {
if (file.isDirectory()) {
mTimeSize.setText("(" + (file.listFiles() != null ? file.listFiles().length : 0) + ")");
} else {
mTimeSize.setText(Formatter.formatFileSize(context, file.length()));
}
}
/**
* 获得SD卡总大小
*
* @return
*/
private static String getSDTotalSize(Context context) {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return Formatter.formatFileSize(context, blockSize * totalBlocks);
}
/**
* 获得sd卡剩余容量,即可用大小
*
* @return
*/
private static String getSDAvailableSize(Context context) {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(context, blockSize * availableBlocks);
}
private void refreshStorageStatus() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
long blockSize = statFs.getBlockSizeLong();
long totalBlocks = statFs.getBlockCountLong();
long availableBlocks = statFs.getAvailableBlocksLong();
String totalSize = Formatter.formatFileSize(this, blockSize * totalBlocks);
String availableSize = Formatter.formatFileSize(this, blockSize * availableBlocks);
textProgressBar.setTextAndProgress("内置存储可用:" + availableSize + "/共:" + totalSize, (int) ((float) availableBlocks / totalBlocks * 100));
} else {
textProgressBar.setTextAndProgress("内置存储不可用", 0);
}
}
@Override
protected Void doInBackground(Void... params) {
filePath = doc.path;
if (!Utils.isDir(doc.mimeType)) {
final boolean allowThumbnail = MimePredicate.mimeMatches(MimePredicate.VISUAL_MIMES, doc.mimeType);
int thumbSize = getResources().getDimensionPixelSize(R.dimen.grid_width);
Point mThumbSize = new Point(thumbSize, thumbSize);
final Uri uri = DocumentsContract.buildDocumentUri(doc.authority, doc.documentId);
final Context context = getActivity();
final ContentResolver resolver = context.getContentResolver();
ContentProviderClient client = null;
try {
if (doc.mimeType.equals(Document.MIME_TYPE_APK) && !TextUtils.isEmpty(filePath)) {
result = ((BitmapDrawable) IconUtils.loadPackagePathIcon(context, filePath, Document.MIME_TYPE_APK)).getBitmap();
} else {
client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, uri.getAuthority());
result = DocumentsContract.getDocumentThumbnail(resolver, uri, mThumbSize, null);
}
} catch (Exception e) {
if (!(e instanceof OperationCanceledException)) {
Log.w(TAG_DETAIL, "Failed to load thumbnail for " + uri + ": " + e);
}
Crashlytics.logException(e);
} finally {
ContentProviderClientCompat.releaseQuietly(client);
}
sizeString = Formatter.formatFileSize(context, doc.size);
}
else{
if(!TextUtils.isEmpty(filePath)){
File dir = new File(filePath);
sizeString = Formatter.formatFileSize(getActivity(), Utils.getDirectorySize(dir));
}
}
return null;
}
private void calculateFolderSize(final boolean deleteDir) {
new AsyncTask<Long, Long, Long>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
fileSize.setSummary("Calculating...");
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
fileSize.setSummary("File Location: " + file.getAbsolutePath() + "\nFile Size: " + Formatter.formatFileSize(getActivity(), aLong));
}
@Override
protected Long doInBackground(Long... params) {
if (deleteDir) {
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
return AppHelper.getFolderSize(file);
}
}.execute();
}
public void setProgressOfSending(long progress,long total){
if(progress<0||total<=0)return;
if(progress>total)return;
progressBar.setMax((int)(total/1024));
progressBar.setProgress((int)(progress/1024));
DecimalFormat dm=new DecimalFormat("#.00");
int percent=(int)(Double.valueOf(dm.format((double)progress/total))*100);
att_right.setText(Formatter.formatFileSize(getContext(),progress)+"/"+Formatter.formatFileSize(getContext(),total)+"("+percent+"%)");
}
@Override
public void show(){
super.show();
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(null);
new Thread(new Runnable() {
@Override
public void run() {
synchronized (DataObbDialog.this){
long data=0,obb=0;
for(AppItem item:list){
long data_item= FileUtil.getFileOrFolderSize(new File(StorageUtil.getMainExternalStoragePath()+"/android/data/"+item.getPackageName()));
long obb_item=FileUtil.getFileOrFolderSize(new File(StorageUtil.getMainExternalStoragePath()+"/android/obb/"+item.getPackageName()));
data+=data_item;
obb+=obb_item;
if(data_item>0) list_data_controllable.add(item);
if(obb_item>0) list_obb_controllable.add(item);
}
final long data_total=data;
final long obb_total=obb;
Global.handler.post(new Runnable() {
@Override
public void run() {
if(data_total==0&&obb_total==0){
cancel();
if(callback!=null)callback.onDialogDataObbConfirmed(list);
return;
}
view.findViewById(R.id.dialog_data_obb_wait_area).setVisibility(View.GONE);
view.findViewById(R.id.dialog_data_obb_show_area).setVisibility(View.VISIBLE);
cb_data.setEnabled(data_total>0);
cb_obb.setEnabled(obb_total>0);
cb_data.setText("Data("+ Formatter.formatFileSize(getContext(),data_total)+")");
cb_obb.setText("Obb("+Formatter.formatFileSize(getContext(),obb_total)+")");
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(DataObbDialog.this);
}
});
}
}
}).start();
}
@Override
public void update(final int position) {
ChatEntity item = list.get(position);
tv_time.setText(DateUtils.formatDate(tv_time.getContext(), item.getTime()));
progress.setProgress(item.getPercent());
File f = new File(item.getContent());
if (f.exists()) {
fileSize.setText(Formatter.formatFileSize(fileSize.getContext(), f.length()));
fileName.setText(f.getName());
} else {
Logger.e("文件不存在:" + item.getContent());
}
}
/**
* 根据 Wifi 获取网络 IP 地址
* @return 网络 IP 地址
*/
@RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
public static String getIpAddressByWifi() {
try {
@SuppressLint("WifiManagerLeak")
WifiManager wifiManager = AppUtils.getWifiManager();
return Formatter.formatIpAddress(wifiManager.getDhcpInfo().ipAddress);
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getIpAddressByWifi");
}
return null;
}
@Override
protected void onPostExecute(Long result) {
if (isCancelled()) {
result = null;
}
if (mSizeView.getTag() == this && result != null) {
mSizeView.setTag(null);
String size = Formatter.formatFileSize(mSizeView.getContext(), result);
mSizeView.setText(size);
mSizes.put(mPosition, result);
}
}
/**
* 根据 Wifi 获取子网掩码 IP 地址
* @return 子网掩码 IP 地址
*/
@RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
public static String getNetMaskByWifi() {
try {
@SuppressLint("WifiManagerLeak")
WifiManager wifiManager = AppUtils.getWifiManager();
return Formatter.formatIpAddress(wifiManager.getDhcpInfo().netmask);
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getNetMaskByWifi");
}
return null;
}