查询本地视频文件流程
流程图
flowchart TD
A[开始] --> B[获取读取权限]
B --> C[检查SD卡是否可用]
C --> D[查询本地视频文件]
D --> E[显示视频列表]
E --> F[结束]
类图
classDiagram
class MainActivity{
- File videoFolder
- ArrayList<String> videoList
- ListView listView
- ArrayAdapter<String> adapter
+ onCreate(Bundle savedInstanceState)
- getPermission()
- checkSDCard()
- queryVideoFiles()
- displayVideoList()
}
详细步骤
- 获取读取权限
在AndroidManifest.xml文件中添加如下权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 检查SD卡是否可用
在MainActivity
类的checkSDCard
方法中,使用以下代码进行检查:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// SD卡可用
} else {
// SD卡不可用
}
- 查询本地视频文件
在MainActivity
类的queryVideoFiles
方法中,使用以下代码查询本地视频文件:
videoFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File[] videoFiles = videoFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".mp4");
}
});
videoList = new ArrayList<>();
for (File videoFile : videoFiles) {
videoList.add(videoFile.getName());
}
- 显示视频列表
在MainActivity
类的displayVideoList
方法中,使用以下代码显示视频列表:
listView = findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, videoList);
listView.setAdapter(adapter);
完整代码示例:
public class MainActivity extends AppCompatActivity {
private File videoFolder;
private ArrayList<String> videoList;
private ListView listView;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getPermission();
checkSDCard();
queryVideoFiles();
displayVideoList();
}
private void getPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
}
private void checkSDCard() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// SD卡可用
} else {
// SD卡不可用
}
}
private void queryVideoFiles() {
videoFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File[] videoFiles = videoFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".mp4");
}
});
videoList = new ArrayList<>();
for (File videoFile : videoFiles) {
videoList.add(videoFile.getName());
}
}
private void displayVideoList() {
listView = findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, videoList);
listView.setAdapter(adapter);
}
}
希望对你有所帮助!