gpt4 book ai didi

android - 在android中使用URI获取文件大小

转载 作者:行者123 更新时间:2023-11-30 00:03:47 27 4
gpt4 key购买 nike

我正在开发 android 视频应用程序,我正在使用 Camera Intent 录制视频并从图库中拍摄视频。录制视频时或从图库中选择视频后,我想知道我拍摄的视频的大小。如果选择的视频大小大于 5MB,我想制定一个逻辑来向用户显示 toast 消息。我制作了不起作用的底部逻辑,并在我尝试从 URI 获取大小的地方给了我 0 值。

提前致谢。

我的逻辑不起作用

java.net.URI juri = new java.net.URI(uri.toString());
File mediaFile = new File(juri.getPath());
long fileSizeInBytes = mediaFile.length();
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;

if (fileSizeInMB > 5) {
Toast.makeText(this,"Video files lesser than 5MB are allowed",Toast.LENGTH_LONG).show();
return;
}

这是我用来从图库获取视频和录制视频的代码。

public void takeVideoFromCamera(){

File mediaFile =new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/myvideo.mp4");

Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
Uri videoUri;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// videoUri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", mediaFile);
videoUri = FileProvider.getUriForFile(this, "i.am.ce.by.ncy.provider", mediaFile);
} else {
videoUri = Uri.fromFile(mediaFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 5491520L);//5*1048*1048=5MB
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,45);
startActivityForResult(intent, VIDEO_CAPTURE);
}

public void takeVideoFromGallery(){
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
long maxVideoSize = 5 * 1024 * 1024; // 10 MB
intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, maxVideoSize);
startActivityForResult(Intent.createChooser(intent,"Select Video"),REQUEST_TAKE_GALLERY_VIDEO);

}

onActivityResult代码

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_OK) {

switch (requestCode) {
case VIDEO_CAPTURE:
if (resultCode == RESULT_OK) {
showVideoImage(data.getData());
// Here I want to know what is the size of my Video File
}
break;
case REQUEST_TAKE_GALLERY_VIDEO:
if (resultCode == RESULT_OK) {
showVideoGallery(data);
// Here I want to know what is the size of my Video File
}
break;
}

最佳答案

AssetFileDescriptor fileDescriptor = getApplicationContext().getContentResolver().openAssetFileDescriptor(uri , "r");
long fileSize = fileDescriptor.getLength();

关于android - 在android中使用URI获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49415012/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com