美文网首页
Android 7.0拍照

Android 7.0拍照

作者: 卓而不群_0137 | 来源:发表于2018-06-07 09:51 被阅读0次

动态授权:

if (Build.VERSION.SDK_INT >=23) {

String[] mPermissionList =new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};

ActivityCompat.requestPermissions(this, mPermissionList,123);

}

public void openCamera(Activity activity) {

//獲取系統版本

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;

// 激活相机

        Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

// 判断存储卡是否可以用,可用进行存储

        if (hasSdcard()) {

SimpleDateFormat timeStampFormat =new SimpleDateFormat(

"yyyy_MM_dd_HH_mm_ss");

String filename = timeStampFormat.format(new Date());

tempFile =new File(Environment.getExternalStorageDirectory(),

filename +".jpg");

if (currentapiVersion <24) {

// 从文件中创建uri

                imageUri = Uri.fromFile(tempFile);

intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

}else {

//兼容android7.0 使用共享文件的形式

                ContentValues contentValues =new ContentValues(1);

contentValues.put(MediaStore.Images.Media.DATA,tempFile.getAbsolutePath());

//检查是否有存储权限,以免崩溃

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)

!= PackageManager.PERMISSION_GRANTED) {

//申请WRITE_EXTERNAL_STORAGE权限

                    Toast.makeText(this,"请开启存储权限",Toast.LENGTH_SHORT).show();

return;

}

imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

}

}

// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA

        activity.startActivityForResult(intent,1);

}

/*

* 判断sdcard是否被挂载

*/

    public static boolean hasSdcard() {

return Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED);

}

拍照成功的回调:

@Override

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

switch (requestCode) {

case 1:

if (resultCode ==RESULT_OK) {

Intent intent =new Intent("com.android.camera.action.CROP");

intent.setDataAndType(imageUri,"image/*");

intent.putExtra("scale",true);

intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

startActivityForResult(intent,2);// 启动裁剪程序

            }

break;

case 2:

if (resultCode ==RESULT_OK) {

try {

Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()

.openInputStream(imageUri));

phto_img.setImageBitmap(bitmap);

}catch (FileNotFoundException e) {

e.printStackTrace();

}

}

break;

}

}

相关文章

网友评论

      本文标题:Android 7.0拍照

      本文链接:https://www.haomeiwen.com/subject/gvwydftx.html