一、调用系统相册图库(sdk23以上需要动态申请权限):
1. 调用系统相机拍照
注:android 7.0(sdk 24)之后拍照发生了改变,需用ContentValues或者FileProvider。
①使用ContentValues
//获取版本
int currentapiVersion = Build.VERSION.SDK_INT; // 激活相机 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//设置图片路径 photo_camera_name = Environment.getExternalStorageDirectory() + "/test" + System.currentTimeMillis() + ".jpg"; File tempFile = new File(photo_camera_name); if (currentapiVersion < 24) { // 从文件中创建uri Uri uri = Uri.fromFile(tempFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); } else { //兼容android7.0 使用共享文件的形式 ContentValues contentValues = new ContentValues(1); contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath()); Uri uri = getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); } // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA startActivityForResult(intent, 100);②使用FileProviderone.在res资源文件夹下创建xml文件夹,再在xml文件夹下面创建文件files_path.xml;写入以下内容
<resources> <paths> <external-path name="camera_photos" path="" /> </paths> </resources>
two.在androidManifests.xml文件中注册provider:
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.example.test.fileprovider" //这里的authorities自己定义,在后面用到 android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_path" /> </provider>
three.photo_camera_name =Environment.getExternalStorageDirectory() + "/test"+ System.currentTimeMillis() + ".jpg"; File file = new File(photo_camera_name); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //Android7.0以上URI if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //添加这一句表示对目标应用临时授权该Uri所代表的文件 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //通过FileProvider创建一个content类型的Uri Uri uri = FileProvider.getUriForFile(PhotoActivity.this, "com.example.test.fileprovider", file);
//这里第二个参数的内容要和前面mainifests.xml文件中注册的provider中的authorities一致 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); } else { intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); } startActivityForResult(intent, 100);
2.从图库选择图片
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT); openAlbumIntent.setDataAndType( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(openAlbumIntent, 101);
3.结果回调
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 拍照 if (requestCode == 100) { if (resultCode == RESULT_CANCELED) { Toast.makeText(context, "取消选择!", Toast.LENGTH_SHORT).show(); return; } // Bundle extras = data.getExtras(); Bitmap bitmap = (Bitmap) extras.get("data")Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE); bitmap.recycle();
}// 从相册获取 if (requestCode == 101) { if (resultCode == RESULT_CANCELED) { Toast.makeText(context, "取消选择!", Toast.LENGTH_SHORT).show(); } else { ContentResolver resolver = getContentResolver(); // 照片的原始资源地址 Uri originalUri = data.getData(); try { // 使用ContentProvider通过URI获取原始图片 Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri); if (photo != null) { // 为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存 Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE); // 释放原始图片占用的内存,防止out of memory异常发生 photo.recycle(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
}
二、从数据库读取:
1.读取相册列表
privateList<AlbumBean>data=newArrayList<>();
ContentResolvercr=context.getContentResolver();
/** * 获取手机中的相册 * * @description: */ private void getPicsFromPhone() { int i = 0; String selection = "0=0) group by (" + MediaStore.Images.Media.BUCKET_DISPLAY_NAME; String[] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, "count(*) as image_count"}; Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, null, MediaStore.Images.Media._ID + " desc"); if (cursor.moveToFirst()) { do { i++; String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)); int count = cursor.getInt(cursor.getColumnIndex("image_count")); //插入获取默认图代码 /* 此处插入下面查询默认图标代码 */</span> Log.i("---" + i + "---", name + "----" + count); String frist = getPhotoList(name); AlbumBean bean = new AlbumBean(name, count,frist); } while (cursor.moveToNext()); } } //获取相册第一张图片做为封面private String getPhotoList(String name) { String path = null; String[] defaltProjection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA};//获取文件夹默认图片信息 Cursor defaltCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, defaltProjection, MediaStore.Images.Media.BUCKET_DISPLAY_NAME + "='" + name + "'", null, MediaStore.Images.Media._ID + " desc");//默认图只要一个 所以只查询一个最新的 int i = 0; while (defaltCursor.moveToFirst()) { i++; int _id = defaltCursor.getInt(defaltCursor.getColumnIndex(MediaStore.Images.Media._ID)); String bigPath = defaltCursor.getString(defaltCursor.getColumnIndex(MediaStore.Images.Media.DATA));//该路径为大图的路径 有时可能我们会去获取缩略图,所以需要查看缩略图 //获得该图片缩略图 String[] projectionThumb = {MediaStore.Images.Thumbnails.DATA}; Cursor cursorprojectionThumb = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projectionThumb, MediaStore.Images.Thumbnails.IMAGE_ID + "=" + _id, null, null);//获取缩略图地址 if (cursorprojectionThumb.moveToFirst()) {//存在缩略图 path = cursorprojectionThumb.getString(cursorprojectionThumb.getColumnIndex(MediaStore.Images.Thumbnails.DATA)); } if (cursorprojectionThumb != null) { cursorprojectionThumb.close(); } if (TextUtils.isEmpty(path)) {//如果不存在缩略图 path = bigPath; } Log.i("---" + i + "---", path); break; } if (defaltCursor != null) { defaltCursor.close(); } return path; }
2.读取相册里的图片
private void getPhotoList(String name) { String[] defaltProjection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA};//获取文件夹默认图片信息 Cursor defaltCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, defaltProjection, MediaStore.Images.Media.BUCKET_DISPLAY_NAME + "='" + name + "'", null, MediaStore.Images.Media._ID + " desc");//默认图只要一个 所以只查询一个最新的 int i = 0; while (defaltCursor.moveToNext()) { i++; int _id = defaltCursor.getInt(defaltCursor.getColumnIndex(MediaStore.Images.Media._ID)); String bigPath = defaltCursor.getString(defaltCursor.getColumnIndex(MediaStore.Images.Media.DATA));//该路径为大图的路径 有时可能我们会去获取缩略图,所以需要查看缩略图 //获得该图片缩略图 String[] projectionThumb = {MediaStore.Images.Thumbnails.DATA}; Cursor cursorprojectionThumb = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projectionThumb, MediaStore.Images.Thumbnails.IMAGE_ID + "=" + _id, null, null);//获取缩略图地址 String path = null; if (cursorprojectionThumb.moveToFirst()) {//存在缩略图 path = cursorprojectionThumb.getString(cursorprojectionThumb.getColumnIndex(MediaStore.Images.Thumbnails.DATA)); } if (cursorprojectionThumb != null) { cursorprojectionThumb.close(); } if (TextUtils.isEmpty(path)) {//如果不存在缩略图 path = bigPath; } Log.i("---" + i + "---", path); } if (defaltCursor != null) { defaltCursor.close(); } }
3.读取手机联系人
private static final String PHONE_BOOK_LABLE = "phonebook_label"; private List<ContactsModel> contactsModelList = new ArrayList<>(); /** * 需要查询的字段 **/ private static final String[] PHONES_PROJECTION = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME , ContactsContract.CommonDataKinds.Phone.NUMBER, PHONE_BOOK_LABLE}; /** * 联系人显示名称 **/ private static final int PHONES_DISPLAY_NAME_INDEX = 0; /** * 电话号码 **/ private static final int PHONES_NUMBER_INDEX = 1;
private void getData(){ ContentResolver mResolver = getContentResolver(); //查询联系人数据,query的参数Phone.SORT_KEY_PRIMARY表示将结果集按Phone.SORT_KEY_PRIMARY排序 Cursor cursor = mResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI , PHONES_PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY); if (cursor != null) { while (cursor.moveToNext()) { ContactsModel model = new ContactsModel(); model.setPhone(cursor.getString(PHONES_NUMBER_INDEX)); if (TextUtils.isEmpty(model.getPhone())) { continue; } model.setName(cursor.getString(PHONES_DISPLAY_NAME_INDEX)); model.setPhonebook_label(cursor.getString(cursor.getColumnIndex(PHONE_BOOK_LABLE))); contactsModelList.add(model); } cursor.close(); } handler.sendEmptyMessage(1); } 4.扫描手机中的文件//参数end表示要扫面的文件类型,如.mp3 ,.mp4,.jpg等private void queryFiles(Context context, String end) { data.clear(); String[] projection = new String[]{MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE }; Cursor cursor = context.getContentResolver().query( Uri.parse("content://media/external/file"), projection, MediaStore.Files.FileColumns.DATA + " like ?", new String[]{"%" + end}, null); if (cursor != null) { if (cursor.moveToFirst()) { int dataindex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA); do { String path = cursor.getString(dataindex); int dot = path.lastIndexOf("/"); String name = path.substring(dot + 1); if (name.lastIndexOf(".") > 0) { name = name.substring(0, name.lastIndexOf(".")); } if (!name.startsWith(".")) { ScanFileBean fileBean = new ScanFileBean(); fileBean.setName(name); fileBean.setPath(path); data.add(fileBean); } } while (cursor.moveToNext()); } } cursor.close(); handler.sendEmptyMessage(1); }