簡體   English   中英

Android Camera Intent無法正常工作-而是啟動圖庫

[英]Android Camera Intent not working - Launching gallery instead

我試圖通過意圖啟動Android camaera,拍照並返回了URI。 應該很簡單,畢竟在SO上有很多關於如何執行此操作的帖子。

但是,我將銀河S3與ICS一起使用,發現當我調用相機意圖時,它會將我帶到圖庫而不是相機。

這是我嘗試過的代碼。

首先是一個簡單的:

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? 還是這些代碼是眾多SO紅色鯡魚之一,因此可以使用任何代碼?

順便說一句,我知道S3無法與MediaStore.EXTRA_OUTPUT一起使用的錯誤。 這對我沒有幫助。 我已經知道如何克服這一障礙。

[編輯]

* *請注意

對於那些閱讀本指南的人來說,這可能是一個嚴重的問題,在使用Camera Intent時需要注意。 盡管啟動相機的活動具有鎖定在清單中的方向。 當設備處於縱向模式時,它將在OnActivityResult之前和之后調用OnCreate ; 因此,將擦除類全局變量。 解決方案是通過* onSaveInstanceStat * e方法保存所有類的全局變量,然后在OnCreate中使用它們在視圖中重新加載並顯示圖像。 從SO收集的信息中,並非所有設備都可以做到這一點,但是每個設備趨向於保持一致。 我的猜測是活動的內存管理取決於可用的硬件和Android平台。 我真的希望情況並非如此,但Android是Android。

[/編輯]

對於使用相機,我使用以下意圖:

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

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>

快照保存在圖庫中的圖像

在此處輸入圖片說明

android.media.action.IMAGE_CAPTURE

android.provider.MediaStore.ACTION_IMAGE_CAPTURE

是一回事。 變量android.provider.MediaStore.ACTION_IMAGE_CAPTURE指向上面的字符串。引用變量而不是字符串的原因是要確保字符串沒有變化。萬一字符串發生變化,則android人也應更改常量,您將能夠知道您引用了錯誤的常量,但是對於字符串,編譯時不會出現錯誤。 我希望它清除。

從圖庫中選擇照片並拍攝新照片的代碼在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>

注意-需要應用程序存儲訪問權限

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM