下面列出了android.provider.MediaStore#ACTION_IMAGE_CAPTURE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void fromCameraInternal(Object object, boolean needCrop) {
if (object == null) return;
cropPath = getCropImagePath();
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
curTempPhotoPath = AppFileHelper.getCameraPath() + AppFileHelper.createShareImageName();
Uri uri = CompatHelper.getUri(new File(curTempPhotoPath));
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
if (CompatHelper.isOverM()) {
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
if (object instanceof Activity) {
((Activity) object).startActivityForResult(cameraIntent, needCrop ? REQUEST_FROM_CAMERA : REQUEST_FROM_CAMERA_WITHO_OUT_CROP);
} else if (object instanceof Fragment) {
((Fragment) object).startActivityForResult(cameraIntent, needCrop ? REQUEST_FROM_CAMERA : REQUEST_FROM_CAMERA_WITHO_OUT_CROP);
}
}
/**
* Register a handler in the package manager for a image capture intent
*/
private void registerMediaStoreIntentHandler()
{
// Add something that will 'handle' the media capture intent
ShadowPackageManager shadowPackageManager = shadowOf(RuntimeEnvironment.application.getPackageManager());
ResolveInfo info = new ResolveInfo();
info.isDefault = true;
ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.packageName = "does.not.matter";
info.activityInfo = new ActivityInfo();
info.activityInfo.applicationInfo = applicationInfo;
info.activityInfo.name = "DoesNotMatter";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
shadowPackageManager.addResolveInfoForIntent(intent, info);
}
private Uri getOutputFilename(String intentType) {
String prefix = "";
String suffix = "";
if (intentType == MediaStore.ACTION_IMAGE_CAPTURE) {
prefix = "image-";
suffix = ".jpg";
} else if (intentType == MediaStore.ACTION_VIDEO_CAPTURE) {
prefix = "video-";
suffix = ".mp4";
}
String packageName = getReactApplicationContext().getPackageName();
File capturedFile = null;
try {
capturedFile = createCapturedFile(prefix, suffix);
} catch (IOException e) {
Log.e("CREATE FILE", "Error occurred while creating the File", e);
e.printStackTrace();
}
return FileProvider.getUriForFile(getReactApplicationContext(), packageName+".fileprovider", capturedFile);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.menu_take_photo)
{
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraFileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraFileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
public static Intent getPickImageIntent(Context context) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent pickIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra("return-data", true);
Uri uri = FileProvider.getUriForFile(context, "cuiliang.android.fileprovider", getTempFile(context));
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intentList = addIntentsToList(context, intentList, pickIntent);
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
context.getString(R.string.pick_image_intent_text));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
@Override
public void showSystemCamera() {
// // 跳转到系统照相机
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(mContext.getPackageManager()) != null) {
// 设置系统相机拍照后的输出路径
// 创建临时文件
mTmpFile = null;
try {
mTmpFile = FileUtils.createTmpFile(mContext);
} catch (IOException e) {
e.printStackTrace();
}
if (mTmpFile != null && mTmpFile.exists()) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
startActivityForResult(cameraIntent, ImageSelector.REQUEST_OPEN_CAMERA);
} else {
showToast(getString(R.string.img_error));
}
} else {
showToast(getString(R.string.msg_no_camera));
}
}
/**
* 选择相机
*/
private void showCamera() {
// 跳转到系统照相机
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager()) != null){
// 设置系统相机拍照后的输出路径
// 创建临时文件
mTmpFile = OtherUtils.createFile(getApplicationContext());
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
startActivityForResult(cameraIntent, REQUEST_CAMERA);
}else{
Toast.makeText(getApplicationContext(),
R.string.msg_no_camera, Toast.LENGTH_SHORT).show();
}
}
/**
* Initiate the existing camera apps
*
* @throws NullPointerException
*/
public void takePicture() throws NullPointerException, IllegalAccessException {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch (mode) {
case ACTIVITY:
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
setUpIntent(takePictureIntent);
activity.startActivityForResult(takePictureIntent,REQUEST_TAKE_PHOTO);
} else {
throw new IllegalAccessException("Unable to open camera");
}
break;
case FRAGMENT:
if (takePictureIntent.resolveActivity(fragment.getActivity().getPackageManager()) != null) {
setUpIntent(takePictureIntent);
fragment.startActivityForResult(takePictureIntent,REQUEST_TAKE_PHOTO);
} else {
throw new IllegalAccessException("Unable to open camera");
}
break;
case COMPAT_FRAGMENT:
if (takePictureIntent.resolveActivity(compatFragment.getActivity().getPackageManager()) != null) {
setUpIntent(takePictureIntent);
compatFragment.startActivityForResult(takePictureIntent,REQUEST_TAKE_PHOTO);
} else {
throw new IllegalAccessException("Unable to open camera");
}
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (cameraResultListener != null && cameraResultListener.getFilePath() != null) {
File tempImageFile = new File(cameraResultListener.getFilePath());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = PSFileProvider.getUriForFile(this, PSFileProvider.getProviderName(this), tempImageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
this.startActivityForResult(intent, REQUEST_CODE);
} else {
Intent result = new Intent();
setResult(Activity.RESULT_CANCELED, result);
finish();
}
}
/**
* 使用相机拍照
*
* @version 1.0
* @author zyh
*/
protected void goCamare() {
if (selectedPicture.size() + 1 > MAX_NUM) {
Toast.makeText(context, "最多选择" + MAX_NUM + "张", Toast.LENGTH_SHORT).show();
return;
}
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri imageUri = getOutputMediaFileUri();
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
}
/**
* @param savingUri Uri to store a high resolution image at. If the user takes the picture using the
* camera the image will be stored at this uri.
* @deprecated Use {@link MediaUtils#createTakePictureIntent(Activity, Uri)}
* Creates a ACTION_IMAGE_CAPTURE photo & ACTION_GET_CONTENT intent. This intent will be
* aggregation of intents required to take picture from Gallery and Camera at the minimum. The
* intent will also be directed towards the apps that are capable of sourcing the image data.
* For e.g. Dropbox, Astro file manager.
**/
public static Intent createTakePictureIntent(Activity ctx, Uri savingUri) {
if (savingUri == null) {
throw new NullPointerException("Uri cannot be null");
}
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = ctx.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, savingUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
return chooserIntent;
}
/**
* 拍照的方法
*/
public void takePicture(Activity activity, int requestCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
if (Utils.existSDCard()) takeImageFile = new File(Environment.getExternalStorageDirectory(), "/DCIM/camera/");
else takeImageFile = Environment.getDataDirectory();
takeImageFile = createFile(takeImageFile, "IMG_", ".jpg");
if (takeImageFile != null) {
// 默认情况下,即不需要指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
// 照相机有自己默认的存储路径,拍摄的照片将返回一个缩略图。如果想访问原始图片,
// 可以通过dat extra能够得到原始图片位置。即,如果指定了目标uri,data就没有数据,
// 如果没有指定uri,则data就返回有数据!
Uri uri;
if (VERSION.SDK_INT <= VERSION_CODES.M) {
uri = Uri.fromFile(takeImageFile);
} else {
/**
* 7.0 调用系统相机拍照不再允许使用Uri方式,应该替换为FileProvider
* 并且这样可以解决MIUI系统上拍照返回size为0的情况
*/
uri = FileProvider.getUriForFile(activity, ProviderUtil.getFileProviderName(activity), takeImageFile);
//加入uri权限 要不三星手机不能拍照
List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
activity.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
Log.e("nanchen", ProviderUtil.getFileProviderName(activity));
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
}
activity.startActivityForResult(takePictureIntent, requestCode);
}
private void camera() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_REQUEST_CODE);
return;
}
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
tempPhotoFile = new File(FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg");
LogUtils.e(tempPhotoFile.getAbsolutePath());
FileUtils.createFile(tempPhotoFile);
Uri uri = FileProvider.getUriForFile(this,
FileUtils.getApplicationId(this) + ".image_provider", tempPhotoFile);
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); //Uri.fromFile(tempFile)
startActivityForResult(cameraIntent, REQUEST_CAMERA);
} else {
Toast.makeText(this, getResources().getString(R.string.open_camera_failure), Toast.LENGTH_SHORT).show();
}
}
private void hookIntoEvents() {
Context context = getContext();
MainThreadBus.get().register(this);
mAppTypeMonitor = new AppTypeMonitor(MediaStore.ACTION_IMAGE_CAPTURE, AlarmClock.ACTION_SET_ALARM);
mAppTypeMonitor.register(context);
mPriorityModeObserver = new GlobalSetting(context, mUiHandler, Constants.ZEN_MODE) {
@Override protected void handleValueChanged(int value) {
mPriorityMode = value;
onPriorityModeChanged(value);
}
};
mPriorityMode = mPriorityModeObserver.getValue();
mPriorityModeObserver.setListening(true);
registeredOtto = true;
}
/**
* This function is called when camera icon is clicked. It send out a
* MediaStore.ACTION_IMAGE_CAPTURE action intent {@link Intent}.
*/
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createPhotoFile();
} catch (IOException ex) {
// Error occurred while creating the File
ZLog.logException(ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mFileUri = FileProvider.getUriForFile(this,
"com.zulip.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// grant uri permissions for lower api levels
List<ResolveInfo> resInfoList = this.getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
this.grantUriPermission(packageName, mFileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
// activity transition animation
ActivityTransitionAnim.transition(ZulipActivity.this);
}
}
}
public void callCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//申请权限 WRITE_EXTERNAL_STORAGE
ContentValues contentValues = new ContentValues(1);
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
Uri mCapturePath = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
cameraPath = getPath(mCapturePath);
File file = new File(cameraPath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturePath);
startActivityForResult(intent, PbChatActivity.ACTIVITY_GET_CAMERA_IMAGE);
}
private void dispatchTakePictureIntent() {
// Open the camera to take a photo.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Action(MediaStore.ACTION_IMAGE_CAPTURE)
Observable<Response> startImageCapture();
@Override
public void showFileChooser(ValueCallback<Uri[]> filePathCallback) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = Utils.createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(Constants.TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[] { takePictureIntent };
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
mActivity.startActivityForResult(chooserIntent, 1);
}
public boolean onShowFileChooser(
WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
requestStoragePermission();
if (!hasStoragePermission())
return false;
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// create the file where the photo should go
File photoFile;
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
// continue only if the file was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
contentSelectionIntent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"image/*", "video/*", "*/*"});
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}