1、实体类Photo.ajva
public class Photo {
private String name;//名称
private String date;//日期
private long size; //大小
private String path;//路径
/**
* 构造函数
*/
public Photo() {
}
public Photo(String name, String date, long size, String path) {
this.name = name;
this.date = date;
this.size = size;
this.path = path;
}
}
2、在AndroidManifest.xml里添加权限
<!-- 读写权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
3、Activity活动里读取手机中的图片
private void initData() {
//读取手机中的相片
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
List<Photo> mPhotoList= new ArrayList<Photo>();
while (cursor.moveToNext()) {
//获取图片的路径
String path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
if(path!=null && path.length() >0) {
//获取图片的名称
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
//获取图片最后修改的日期
File file = new File(path);
long modifieTime = file.lastModified();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String date = sdf.format(new Date(modifieTime));
//获取图片的大小
long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.SIZE));
Photo photo = new Photo(name, date, size, path);
mPhotoList.add(photo);
}
}
mPhotoList = sortList(mPhotoList);
}
/**
* List按照时间降序排列
* @param L
* @return
*/
private List<Photo> sortList(List<Photo> L){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Photo temp = new Photo();
//冒泡排序,大的时间在数组的前列
for(int i=0; i<L.size()-1; i++){
for(int j=i+1; j<L.size();j++){
String date1=L.get(i).getDate();
String date2=L.get(j).getDate();
Date d1=sdf.parse(date1,new ParsePosition(0));
Date d2=sdf.parse(date2,new ParsePosition(0));
boolean flag = d1.before(d2);
//flag=true为降序,flag=flase为升序
if (flag){
temp = L.get(i);
L.set(i, L.get(j));
L.set(j, temp);
}
}
}
return L;
}
最后分享一下项目示例代码,需要的可自行下载: