初次发布文章,如有不详之处请各位看官多多指点。
直奔主题,该文章主要内容是通过列表展示指定路径文件夹下的图片和视频,通过点击子项打开图片或者播放视频,该功能并不复杂,但是在Android7.0之后多了一些权限相关的坑。仅此记录一下。
话不多说先放代码。
package com.serenegiant.usbcameratest8.activity;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.serenegiant.usbcameratest8.Bean.PermissionsUtils;
import com.serenegiant.usbcameratest8.R;
import java.io.File;
/**
*选择进入图片还是视频列表
*/
public class SelectActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "SelectActivity";
ImageView goBack;
ImageView selectPhoto;
ImageView selectVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
goBack=(ImageView)findViewById(R.id.go_back);
selectPhoto=(ImageView)findViewById(R.id.select_photo);
selectVideo=(ImageView)findViewById(R.id.select_video);
requestPermisson();
goBack.setOnClickListener(this);
selectVideo.setOnClickListener(this);
selectPhoto.setOnClickListener(this);
File videoDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "USBCameraTest");
File photoDir=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "USBCameraTest");
Log.e(TAG,"视频的路径:"+videoDir.getAbsolutePath()+"\n"+"图片的路径:"+photoDir.getAbsolutePath());
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.go_back:
startActivity(new Intent(SelectActivity.this,CameraActivity.class));
finish();
break;
case R.id.select_photo:
Intent photoIntent=new Intent(SelectActivity.this,MediaListActivity.class);
photoIntent.putExtra("type","photo");
startActivity(photoIntent);
break;
case R.id.select_video:
Intent videoIntent=new Intent(SelectActivity.this,MediaListActivity.class);
videoIntent.putExtra("type","video");
startActivity(videoIntent);
break;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(SelectActivity.this,CameraActivity.class));
}
private void requestPermisson(){
String[] permissions=new String[]{Manifest.permission.READ_CALENDAR,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO,
};
PermissionsUtils.getInstance().chekPermissions(SelectActivity.this,permissions,permissionsResult);
}
//创建监听权限的接口对象
PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
@Override
public void passPermissons() {
}
@Override
public void forbitPermissons() {
Toast.makeText(SelectActivity.this, "权限不通过!", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//就多一个参数this
PermissionsUtils.getInstance().onRequestPermissionsResult(SelectActivity.this, requestCode, permissions, grantResults);
}
}
该段代码可以忽略 为了不显得太突兀才加上,对应的界面如下:
----------------------------------------------------------------------------------- 分割线-----------------------------------------------------------------------
package com.serenegiant.usbcameratest8.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;
import com.serenegiant.usbcameratest8.R;
import com.serenegiant.usbcameratest8.adapter.MediaRecycleAdapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MediaListActivity extends AppCompatActivity {
private static final String TAG = "MediaListActivity";
private RecyclerView mediaRecycleView;
private TextView isEmpty,titlrName;
private MediaRecycleAdapter mediaRecycleAdapter;
private ArrayList<String> pathList;
private boolean isVideo;
File videoDir;
File photoDir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_list);
// Toolbar toolbar=(Toolbar)findViewById(R.id.titleName);
isEmpty=(TextView)findViewById(R.id.is_empty);
titlrName=(TextView)findViewById(R.id.title);
FrameLayout back=(FrameLayout)findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
initParameters();
initRecycle();
recycleItemOnClick();
}
/**
* 获取存储图片和视频的路径
*/
public void initParameters(){
Intent intent=getIntent();
if (intent!=null){
String type=intent.getStringExtra("type");
if (type.equals("photo")){
isVideo=false;
titlrName.setText("图片");
}else {
titlrName.setText("视频");
isVideo=true;
}
}
videoDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "USBCameraTest");
photoDir=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "USBCameraTest");
Log.e(TAG,"视频的路径:"+videoDir.getAbsolutePath()+"\n"+"图片的路径:"+photoDir.getAbsolutePath());
}
public void initRecycle(){
mediaRecycleView=(RecyclerView)findViewById(R.id.media_recycle);
mediaRecycleAdapter=new MediaRecycleAdapter(getApplicationContext(),getPathList(isVideo));
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
mediaRecycleView.setLayoutManager(layoutManager);
mediaRecycleAdapter.isVideo(isVideo);
mediaRecycleView.setAdapter(mediaRecycleAdapter);
}
/**
* 获得所有图片或者视频的路径
* @param isVideo
* @return
*/
public List<String> getPathList(boolean isVideo) {
pathList=new ArrayList<>();
String pathStrig;
if (isVideo){
pathStrig=videoDir.getAbsolutePath(); //视频文件夹的途径
}else {
pathStrig=photoDir.getAbsolutePath(); //图片文件夹的路径
}
Log.e(TAG,"isVideo"+isVideo);
File media=new File(pathStrig);
Log.e(TAG,"media是否是文件夹"+media.isDirectory());
if (media.isDirectory()){
File[] files=media.listFiles();
Log.e(TAG,"文件数量"+files.length);
for (int i=0;i<files.length;i++){
File file=files[i];
if (file.exists()){
pathList.add(file.getAbsolutePath());
}
}
}
Log.e(TAG,"图片或者视频的数量:"+pathList.size());
if (pathList.size()>0){
mediaRecycleView.setVisibility(View.VISIBLE);
isEmpty.setVisibility(View.GONE);
}else {
}
return pathList;
}
/**
* recycleView子项的点击事件
*/
private void recycleItemOnClick(){
mediaRecycleAdapter.setOnItemClickListener(new MediaRecycleAdapter.ItemClickListener() {
@Override
public void onIntemClick(View view, int position) {
if (isVideo){
Intent intent=new Intent(MediaListActivity.this, VideoActivity.class);
intent.putExtra("videoPath",pathList.get(position));
intent.putStringArrayListExtra("videoPathList", pathList);
startActivity(intent);
}else {
Intent photoInten=new Intent();
String path=pathList.get(position); //图片路径
File file=new File(path);
Uri uri;
photoInten.setAction(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT>=24){
uri= FileProvider.getUriForFile(getApplicationContext(),getPackageName()+".provider",file);
photoInten.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
uri=Uri.fromFile(file);
}
photoInten.setDataAndType(uri,"image/*");
startActivity(photoInten);
}
}
});
}
}
该段代码中开始出现第一个坑,在Android7.0及以后使用系统图片查看器打开相应的图片将会报错,正确处理方式如下:
第一步:在AndroidManifest中添加以下内容
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.serenegiant.usbcameratest8.provider" <!-- 自定义一般使用包名-->
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_paths"
tools:replace="android:resource" />
</provider>
第二步:在res文件夹下新建xml文件夹,并新建xml文件,名字要和AndroidManifest中引用的名字一样,如下所示
xxx.xml中的代码:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="name" path="" />
</paths>
第三步:代码块中的写法,和Android7.0之前的有很大区别
Intent photoInten=new Intent();
String path=pathList.get(position); //图片路径
File file=new File(path);
Uri uri;
photoInten.setAction(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT>=24){
uri= FileProvider.getUriForFile(getApplicationContext(),getPackageName()+".provider",file);
photoInten.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
uri=Uri.fromFile(file);
}
photoInten.setDataAndType(uri,"image/*");
startActivity(photoInten);
以上代码的功能界面如下:
-----------------------------------------------------分割线-------------------------------------------------------
接下来就是视频播放的功能
public class VideoActivity extends AppCompatActivity {
private static final String TAG = "VideoActivity";
private String videoPath;
private int index;
private List<String> pathList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
requestWindowFeature(Window.FEATURE_NO_TITLE); //隐藏状态栏
int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN; // 定义全屏参数
//设置当前窗体为全屏显示
window.setFlags(flag, flag);
setContentView(R.layout.activity_video);
initParameters();
playVideo();
}
/**
* 接收参数
*/
public void initParameters(){
final Intent intent=getIntent();
final int position=intent.getIntExtra("position",0);
index=position;
videoPath=intent.getStringExtra("videoPath");
pathList=intent.getStringArrayListExtra("videoPathList");
}
/**
* 播放视频
*/
public void playVideo(){
final VideoView videoView=(VideoView)findViewById(R.id.videoView);
MediaController mediaController=new MediaController(this);
if (videoPath!=null){
videoView.setVideoPath(videoPath);
videoView.setMediaController(mediaController);
mediaController.setMediaPlayer(videoView);
videoView.requestFocus();
videoView.start();
mediaController.setPrevNextListeners(new View.OnClickListener() {
@Override
public void onClick(View view) {
index=index+1;
if (index<pathList.size()){
videoView.setVideoPath(pathList.get(index));
Log.e(TAG,"下一集"+index);
}else {
Toast.makeText(VideoActivity.this,"没有下一部",Toast.LENGTH_SHORT).show();
}
}
}, new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e(TAG,"上一集");
index=index-1;
if (index>=0){
videoView.setVideoPath(pathList.get(index));
}else {
Toast.makeText(VideoActivity.this,"没有上一部",Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
结束