开发语言:Java
开发生态:Android
一、申请权限
在清单AndroidManifest.xml中添加
<!-- 访问网络状态-->
<uses-permission android:name="android.permission.INTERNET" />
二、功能实现
/**
* 获取网络资源文件大小
*/
private void getNetworkFileSize() {
final Handler handler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
String fileSize = msg.getData().getString("fileSize");
Log.d("fileSize", fileSize);
}
};
String fileUrl = call.argument("fileUrl");
if (fileUrl == null) {
return;
}
if (fileUrl.length() == 0) {
return;
}
URL url = null;
try {
url = new URL(fileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url == null) {
return;
}
final URL finalUrl = url;
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection urlConnection = (HttpURLConnection) finalUrl.openConnection();
int fileLength = urlConnection.getContentLength();
Bundle bundle = new Bundle();
bundle.putString("fileSize", "文件大小:" + formatFileSize(fileLength));
Message message = handler.obtainMessage();
message.setData(bundle);
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 转换文件大小
*
* @param fileS
* @return
*/
public static String formatFileSize(int fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString;
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1024 * 1024) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1024 * 1024 * 1024) {
fileSizeString = df.format((double) fileS / (1024 * 1024)) + "MB";
} else {
fileSizeString = df.format((double) fileS / (1024 * 1024 * 1024)) + "GB";
}
return fileSizeString;
}
小白的进阶之路,感谢大家的支持!