【问题标题】:Android Camera Intent not working - Launching gallery insteadAndroid Camera Intent 不起作用 - 改为启动图库
【发布时间】:2013-05-27 14:35:07
【问题描述】:

我正在尝试通过意图启动 Android 摄像头,拍照并返回 URI。应该很简单吧,毕竟在 SO 上有很多关于如何做到这一点的帖子。

但是,我使用的是带有 ICS 的 Galaxy S3,发现当我调用相机意图时,它会将我带到画廊而不是相机。

这是我尝试过的代码。

首先是一个简单的:

public static final int REQUEST_CODE_CAMERA = 1337;
.
.
. 
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
startActivityForResult(intent, REQUEST_CODE_CAMERA); 

这不起作用。所以我尝试了Vogella.com的例子

private static final int REQUEST_CODE = 1;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);

我也读过有人建议使用不同的请求代码,例如 1888、1337 和 2500。难道没有通用的请求代码或基于框架的静态 int 我可以使用吗?或者这些代码是众多红鲱鱼之一,因此可以使用任何代码?

顺便说一句,我知道 S3 无法与 MediaStore.EXTRA_OUTPUT 一起使用的错误。这不是我需要的帮助。我已经知道如何克服这个障碍。

[编辑]

**请注意

对于那些阅读这个方向的人来说可能是一个严重的问题,在使用相机意图时需要注意。尽管启动相机的活动在清单中锁定了它的方向。当设备处于纵向模式时,它会在 OnActivityResult 前后调用 OnCreate;因此类全局变量被擦除。解决方案是通过 *onSaveInstanceStat*e 方法保存所有类全局变量,并在 OnCreate 中使用这些变量重新加载并在视图中显示图像。从 SO 收集的信息来看,并非所有设备都会这样做,但每个设备往往是一致的。我的猜测是活动的内存管理取决于可用的硬件和 Android 平台。我真希望不是这样,但 Android 就是 Android。

[/编辑]

【问题讨论】:

  • 我有一个 s3,我使用 MediaStore.EXTRA_OUTPUT,我没有遇到任何问题
  • 您可能没有 ICS 并已更新。无论如何,不​​要转移我原来的问题,这不是这个。
  • 我的手机里有果冻豆。
  • “requestCode”由您决定。它的值在 Activity#onActivityResult(..) 中传递回您的应用程序。它用于区分哪个 Activity 将结果返回给您的应用。

标签: android android-intent camera


【解决方案1】:

为了使用相机,我使用以下意图:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

【讨论】:

  • 有趣的是它的工作原理。所以这引出了一个问题,为什么有这么多使用 Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);?? 的建议?显然他们是不正确的?或者有什么时候使用这个,什么时候使用你建议的?
  • 它在 Nexus S 和 ASUS Transformer 平板电脑上进行了测试。没有在 S3 上尝试过。
  • @AndrewS 我刚刚在手机上测试了它,通过查看图库中捕获的图像查看答案和快照。
  • 这工作并允许相机显示。这就引出了一个问题,为什么有两种调用相机的方法,有什么区别?
  • @AndrewS 我遵循了文档,代码对我来说很好。所以我建议你忘记替代方案并遵循文档。
【解决方案2】:

MainActivity.java

public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888; 
private ImageView imageView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.imageView = (ImageView)this.findViewById(R.id.imageView1);
    Button photoButton = (Button) this.findViewById(R.id.button1);
    photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 
            File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyCameraImages");
            imagesFolder.mkdirs();   
            File image = new File(imagesFolder, "image.jpg");
            Uri uriSavedImage = Uri.fromFile(image);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);

        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        imageView.setImageBitmap(photo);        
} 
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="79dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="26dp"
    android:text="StartCamera" />

</RelativeLayout>

保存在图库中的图像快照

【讨论】:

  • 不,没有具体原因。 developer.android.com/guide/topics/media/camera.html。在示例代码 sn-p 他们有这个私有静态 final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;.
  • 所以在调用 StartActitivtyForIntent 行后可以将附加内容添加到意图中吗?
  • 好吧,我不会遇到任何问题。
  • 您的权利,将附加内容放在 StartActivity 之后可以避免空指针异常。你的代码有点工作,但有一些奇怪的副作用。例如,当它用图像填充我的 imageView 时,屏幕暂时处于错误的方向。然后它会自行纠正,图像消失。这很奇怪,因为我只在清单中将屏幕锁定为纵向模式。
  • @HarshAgrawal 您应该发布一个带有相关代码和堆栈跟踪的新问题。在最近的操作系统上,您需要使用 FileProvider
【解决方案3】:

android.media.action.IMAGE_CAPTURE

android.provider.MediaStore.ACTION_IMAGE_CAPTURE

是一回事。变量 android.provider.MediaStore.ACTION_IMAGE_CAPTURE 指的是上面的字符串。引用变量而不是字符串的原因是要确保字符串没有变化。如果字符串发生变化,android人也应该改变常量,你应该能够知道您指的是错误的常量,但是对于字符串,编译时不会出现错误。 我希望它清除。

【讨论】:

    【解决方案4】:

    SDK 24 或更高版本也支持从图库中选择照片并拍摄新照片的代码

    活动

    private File filePathImageCamera;
    private Uri imagePath;
    private static final int IMAGE_GALLERY_REQUEST = 2;
    private static final int IMAGE_CAMERA_REQUEST = 3;
    private String imageFilePath;
    
    private void selectImage() {
    
    
            final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
    
            AlertDialog.Builder builder = new AlertDialog.Builder(DocumentActivity.this);
    
            builder.setTitle("Upload Photo!");
    
            builder.setItems(options, new DialogInterface.OnClickListener() {
    
                @Override
    
                public void onClick(DialogInterface dialog, int item) {
    
                    if (options[item].equals("Take Photo")) {
                        photoCameraIntent();
                    } else if (options[item].equals("Choose from Gallery")) {
                        photoGalleryIntent();
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
    
                }
    
            });
    
            builder.show();
    
        }
    
     private void photoCameraIntent() {
    
            Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uri = null;
    
            try {
                filePathImageCamera = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
    
            }
    
    
            if (pictureIntent.resolveActivity(getPackageManager()) != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    
                    //Create a file to store the image
    
                    if (filePathImageCamera != null) {
                        Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", filePathImageCamera);
                        pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                photoURI);
                        startActivityForResult(pictureIntent,
                                IMAGE_CAMERA_REQUEST);
                    }
    
    
                } else {
    
    
                    if (filePathImageCamera != null) {
                        uri = Uri.fromFile(filePathImageCamera);
    
                        pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        startActivityForResult(pictureIntent, IMAGE_CAMERA_REQUEST);
                    }
    
    
                }
            }
    
        }
    
        private File createImageFile() throws IOException {
            String timeStamp =
                    new SimpleDateFormat("yyyyMMdd_HHmmss",
                            Locale.getDefault()).format(new Date());
            String imageFileName = "IMG_" + timeStamp + "_";
            File storageDir =
                    getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    
            // Create the storage directory if it does not exist
            if (!storageDir.exists() && !storageDir.mkdirs()){
                Log.d("error", "failed to create directory");
            }
    
            File image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
    
            imageFilePath = image.getAbsolutePath();
            return image;
        }
    
        private void photoGalleryIntent() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Get Image From"), IMAGE_GALLERY_REQUEST);
        }
    
    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
            if (requestCode == IMAGE_GALLERY_REQUEST) {
                if (resultCode == RESULT_OK) {
    
                    imagePath = data.getData();
    
    
                    Glide.with(MainActivity.this).load(imagePath).into(imageview);
    
    
    
    
    
    
    
                }
            } else if (requestCode == IMAGE_CAMERA_REQUEST) {
                if (resultCode == RESULT_OK) {
                    if (filePathImageCamera != null && filePathImageCamera.exists()) {
    
                        imagePath = Uri.fromFile(filePathImageCamera);
    
    
                        Glide.with(MainActivity.this).load(imagePath).into(imageview);
    
    
    
    
                    } 
                }
            }
    
        }
    

    清单

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
     <application>
    
      <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="${applicationId}.provider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths" />
            </provider>
    
    </application>
    

    在 res/xml 目录下新建文件 provider_paths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
    
        <external-path name="my_images"
            path="Android/data/your_package_name/files/Pictures" />
    
    </paths>
    

    注意 - 需要应用存储访问权限

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      相关资源
      最近更新 更多