Android之操作相册

时间:2021-12-23 16:00:49

获取手机中的图片的绝对路径并且区分出每个文件夹下的路径:

存放图片绝对路径的文件夹的名字和存放绝对路径的List 实体类如下:

 import java.util.ArrayList;
import java.util.List; public class ImagePath {
private String pakagePath;
private List<String> listPth = new ArrayList<String>(); public String getPakagePath() {
return pakagePath;
}
public void setPakagePath(String pakagePath) {
this.pakagePath = pakagePath;
}
public List<String> getListPth() {
return listPth;
}
public void setListPth(List<String> listPth) {
this.listPth = listPth;
} }

将手机中的图片绝对路径按包名区分开:

     private ContentResolver contentResolver;
private Button button;
private Uri uri;
private List<ImagePath> imagePaths;
private List<ImagePath> getImgPath() {
imagePaths = new ArrayList<ImagePath>();
contentResolver = this.getContentResolver();
uri = Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
Set<String> set = new TreeSet<String>();
List<String> lsPsth = new ArrayList<String>();
while (cursor.moveToNext()) {
//获取绝对路径
String path = cursor.getString(cursor.getColumnIndex(Media.DATA));
//将绝对路径添加到list中
lsPsth.add(path);
//获取包名
String pakageName = cursor.getString(cursor.getColumnIndex(Media.BUCKET_DISPLAY_NAME));
//将包名添加到set中
set.add(pakageName);
}
//set转换成数组
String[] str =set.toArray(new String[set.size()]);
//循环装有包名的数组
for (int i = 0; i < str.length; i++) {
//创建一个ImagePath对象,用于存储某个包下的所有绝对路径(包含包名)
ImagePath imagePath = new ImagePath();
//创建一个ImagePath对象,用于存储某个包下的所有绝对路径(不包含包名)
List<String> listpath = new ArrayList<String>();
//将str数组中的第一个包名存入到imagePath对象中
imagePath.setPakagePath(str[i]);
//循环lsPsth中的所有绝对路径
for (int k = 0; k < lsPsth.size(); k++) {
//判断lsPathget(k)当前这条绝对路径是否是str[i]包名下的绝对路径
if(getPakageNameByPath(lsPsth.get(k)).equals(str[i])){
//如果是存入listpath中
listpath.add(lsPsth.get(k));
}
}
//将区分出来的对局路径存入到对用的包名的imagePath对象中
imagePath.setListPth(listpath);
//将该对象存入imagePaths集合中
imagePaths.add(imagePath);
}
return imagePaths;
}
     /**
* 根据据对路径获取该路径的包名
* @param path
* @return
*/
public String getPakageNameByPath(String path){
String pkgName = null;
if(path.length()>0){
String[] str = path.split("/");
pkgName = str[str.length-2];
}
return pkgName;
}

未完....