我是靠谱客的博主 清爽钢铁侠,最近开发中收集的这篇文章主要介绍android7.0选取照片,Android拍照选取照片 适配7.0,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

public class EditProfile extends AppCompatActivity {

private static final int PICK_IMAGE = 100;

private Button image;

private ImageView profile;

private DatabaseHelper db;

SharedPreferences sprfMain;

//调取系统摄像头的请求码

private static final int MY_ADD_CASE_CALL_PHONE = 6;

//打开相册的请求码

private static final int MY_ADD_CASE_CALL_PHONE2 = 7;

Uri uri;

String username;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_edit_profile);

sprfMain = getSharedPreferences("config",0);

db = new DatabaseHelper(EditProfile.this);

username = sprfMain.getString("username", "");

image = findViewById(R.id.Image);

profile = findViewById(R.id.Profile);

profile.setImageBitmap(db.getImage(username));

image.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

UpdatePhoto();

}

});

Button back = findViewById(R.id.Back);

back.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

int userType = sprfMain.getInt("type",0);

switch (userType){

//Normal user

case 0:

break;

// Club user

case 1:

break;

// System admin

case 2:

break;

}

}

});

}

public void UpdatePhoto() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.dialog_select_photo, null);//获取自定义布局

builder.setView(layout);

final AlertDialog dlg = builder.create();

Window window = dlg.getWindow();

window.setGravity(Gravity.BOTTOM);

//设置点击外围消散

dlg.setCanceledOnTouchOutside(true);

dlg.show();

WindowManager m = getWindowManager();

Display d = m.getDefaultDisplay(); //为获取屏幕宽、高

WindowManager.LayoutParams p = dlg.getWindow().getAttributes(); //获取对话框当前的参数值

p.width = d.getWidth(); //宽度设置为屏幕

window.setBackgroundDrawable(new ColorDrawable(0));

TextView button1 = layout.findViewById(R.id.photograph);

TextView button2 = layout.findViewById(R.id.photo);

TextView button3 = layout.findViewById(R.id.cancel);

button1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

//"点击了照相";

// 6.0之后动态申请权限 摄像头调取权限,SD卡写入权限

if (ContextCompat.checkSelfPermission(EditProfile.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED

&& ContextCompat.checkSelfPermission(EditProfile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(EditProfile.this,

new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},

MY_ADD_CASE_CALL_PHONE);

} else {

try {

//有权限,去打开摄像头

takePhoto();

} catch (IOException e) {

e.printStackTrace();

}

}

dlg.dismiss();

}

});

button2.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

//"点击了相册");

// 6.0之后动态申请权限 SD卡写入权限

if (ContextCompat.checkSelfPermission(EditProfile.this,

Manifest.permission.WRITE_EXTERNAL_STORAGE)

!= PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(EditProfile.this,

new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},

MY_ADD_CASE_CALL_PHONE2);

} else {

choosePhoto();

}

dlg.dismiss();

}

});

button3.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

dlg.dismiss();

}

});

}

private void takePhoto() throws IOException {

Intent intent = new Intent();

intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

// 获取文件

File file = createFileIfNeed("UserIcon.png");

//拍照后原图回存入此路径下

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {

uri = Uri.fromFile(file);

} else {

/**

* 7.0 调用系统相机拍照不再允许使用Uri方式,应该替换为FileProvider

* 并且这样可以解决MIUI系统上拍照返回size为0的情况

*/

uri = FileProvider.getUriForFile(this, "com.example.club.provider", file);

}

intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

startActivityForResult(intent, 1);

}

// 在sd卡中创建一保存图片(原图和缩略图共用的)文件夹

private File createFileIfNeed(String fileName) throws IOException {

String fileA = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/nbinpic";

File fileJA = new File(fileA);

if (!fileJA.exists()) {

fileJA.mkdirs();

}

File file = new File(fileA, fileName);

if (!file.exists()) {

file.createNewFile();

}

return file;

}

/**

* 打开相册

*/

private void choosePhoto() {

//这是打开系统默认的相册(就是你系统怎么分类,就怎么显示,首先展示分类列表)

Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(picture, 2);

}

/**

* 申请权限回调

*

* @param requestCode

* @param permissions

* @param grantResults

*/

@Override

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

if (requestCode == MY_ADD_CASE_CALL_PHONE) {

if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

try {

takePhoto();

} catch (IOException e) {

e.printStackTrace();

}

} else {

//"权限拒绝");

// TODO: 2018/12/4 这里可以给用户一个提示,请求权限被拒绝了

}

}

if (requestCode == MY_ADD_CASE_CALL_PHONE2) {

if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

choosePhoto();

} else {

//"权限拒绝");

// TODO: 2018/12/4 这里可以给用户一个提示,请求权限被拒绝了

}

}

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == 1 && resultCode != Activity.RESULT_CANCELED) {

try {

Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

profile.setImageBitmap(bitmap);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

} else if (requestCode == 2 && resultCode == Activity.RESULT_OK

&& null != data) {

try {

String filePathByUri = FileUtil.getFilePathByUri(EditProfile.this, data.getData());

Glide.with(EditProfile.this).load(filePathByUri).into(profile);

} catch (Exception e) {

//"上传失败");

}

}

}

public byte[] imgToByte(Bitmap bitmap) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

return baos.toByteArray();

}

}

File'U't'l

public class FileUtil {

/**

* 根据URI获取文件真实路径(兼容多张机型)

* @param context

* @param uri

* @return

*/

public static String getFilePathByUri(Context context, Uri uri) {

if ("content".equalsIgnoreCase(uri.getScheme())) {

int sdkVersion = Build.VERSION.SDK_INT;

if (sdkVersion >= 19) { // api >= 19

return getRealPathFromUriAboveApi19(context, uri);

} else { // api < 19

return getRealPathFromUriBelowAPI19(context, uri);

}

} else if ("file".equalsIgnoreCase(uri.getScheme())) {

return uri.getPath();

}

return null;

}

/**

* 适配api19及以上,根据uri获取图片的绝对路径

*

* @param context 上下文对象

* @param uri 图片的Uri

* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null

*/

@SuppressLint("NewApi")

private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {

String filePath = null;

if (DocumentsContract.isDocumentUri(context, uri)) {

// 如果是document类型的 uri, 则通过document id来进行处理

String documentId = DocumentsContract.getDocumentId(uri);

if (isMediaDocument(uri)) { // MediaProvider

// 使用':'分割

String type = documentId.split(":")[0];

String id = documentId.split(":")[1];

String selection = MediaStore.Images.Media._ID + "=?";

String[] selectionArgs = {id};

//

Uri contentUri = null;

if ("image".equals(type)) {

contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

} else if ("video".equals(type)) {

contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

} else if ("audio".equals(type)) {

contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

}

filePath = getDataColumn(context, contentUri, selection, selectionArgs);

} else if (isDownloadsDocument(uri)) { // DownloadsProvider

Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));

filePath = getDataColumn(context, contentUri, null, null);

}else if (isExternalStorageDocument(uri)) {

// ExternalStorageProvider

final String docId = DocumentsContract.getDocumentId(uri);

final String[] split = docId.split(":");

final String type = split[0];

if ("primary".equalsIgnoreCase(type)) {

filePath = Environment.getExternalStorageDirectory() + "/" + split[1];

}

}else {

//Log.e("路径错误");

}

} else if ("content".equalsIgnoreCase(uri.getScheme())) {

// 如果是 content 类型的 Uri

filePath = getDataColumn(context, uri, null, null);

} else if ("file".equals(uri.getScheme())) {

// 如果是 file 类型的 Uri,直接获取图片对应的路径

filePath = uri.getPath();

}

return filePath;

}

/**

* 适配api19以下(不包括api19),根据uri获取图片的绝对路径

*

* @param context 上下文对象

* @param uri 图片的Uri

* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null

*/

private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {

return getDataColumn(context, uri, null, null);

}

/**

* 获取数据库表中的 _data 列,即返回Uri对应的文件路径

*

* @return

*/

private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

String path = null;

String[] projection = new String[]{MediaStore.Images.Media.DATA};

Cursor cursor = null;

try {

cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);

if (cursor != null && cursor.moveToFirst()) {

int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);

path = cursor.getString(columnIndex);

}

} catch (Exception e) {

if (cursor != null) {

cursor.close();

}

}

return path;

}

/**

* @param uri the Uri to check

* @return Whether the Uri authority is MediaProvider

*/

private static boolean isMediaDocument(Uri uri) {

return "com.android.providers.media.documents".equals(uri.getAuthority());

}

private static boolean isExternalStorageDocument(Uri uri) {

return "com.android.externalstorage.documents".equals(uri.getAuthority());

}

/**

* @param uri the Uri to check

* @return Whether the Uri authority is DownloadsProvider

*/

private static boolean isDownloadsDocument(Uri uri) {

return "com.android.providers.downloads.documents".equals(uri.getAuthority());

}

}

provider

tools:replace="android:authorities"

android:name="androidx.core.content.FileProvider"

android:authorities="com.example.club.provider"

android:exported="false"

android:grantUriPermissions="true">

tools:replace="android:resource"

android:name="android.support.FILE_PROVIDER_PATHS"

android:resource="@xml/flie_path" />

最后

以上就是清爽钢铁侠为你收集整理的android7.0选取照片,Android拍照选取照片 适配7.0的全部内容,希望文章能够帮你解决android7.0选取照片,Android拍照选取照片 适配7.0所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部