Last active
March 17, 2018 02:58
-
-
Save rosuH/beda0649610b45f56edd5879344e47cb to your computer and use it in GitHub Desktop.
Launch camera to take photo by intent.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyFregment extends Fregment { | |
private static final int REQUEST_PHOTO = 2; | |
@Override | |
public View onCreateView(layoutflater inflater, ViewGroup container, Bundle savedinstanceState) { | |
mPhotoButton = (imageButton) v.findViewById(R.id.camera); | |
// 默认只能拍出低分辨率图片 | |
// 要想获得全尺寸照片,要让它使用文件系统存储图片 | |
// 需要传入保存在 MediaStore.EXTRA_OUTPUT 中的 Uri,该 Uri 会指向 FileProvider 提供的位置 | |
final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); | |
// 检查是否有地方存储照片,以及设备上是否有安装相机应用 | |
boolean canTakePhoto = mPhotoFile != null && captureImage.resolveActivity(PackageManager) != null; | |
mPhotoButton.setEnabled(canTakePgoto); | |
mPhotoButton.setOnclickListener(new View.OnclickListener() { | |
@Override | |
// 传入保存在 MediaStore.EXTRA_OUTPUT 中的 Uri,该 Uri 会指向 FileProvider 提供的位置 | |
Uri uri = FileProvider.getUriForFile(getActivity(), "com.example.android.fileprovider", mPhotoFile); | |
captureImage.putExtra(MediaStore.EXTRA_OUT_PUT, uri); | |
// 为相机授予权限 | |
// 将 FLAG_GRANT_WRITE_URI_PERMISSION 权限授予所有 cameraImage intent 目标 activity | |
// 以允许他们在 uri 指定位置写入文件 | |
List<ResolveInfo> cameraActivities = getActivity().getPackageManager().queryIntentActivities( | |
captureImage, PackageManager.MATH_DEFAULT_ONLY); | |
for (ResolveInfo activity : cameraActivities) { | |
getActovoty.grantUriPermission(activity.activityInfo.packageName, | |
uri, Intent.FLAG_FLAG_GRANT_WRITE_URI_PERMISSION); | |
} | |
startActivityForResult(captureImage, REQUEST_PHOTO); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment