1. 程式人生 > >Android呼叫系統照相機返回intent為空原因分析

Android呼叫系統照相機返回intent為空原因分析

1.在呼叫android系統相簿時,使用的是如下方式:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/");

    startActivityForResult(intent,1);

 在onActivityResult 中通過data獲取資料可以正常獲取:

if (requestCode == 1)
        {
            Uri uri = null;
            if (null != data || resultCode == RESULT_OK)
            {
                uri = data.getData();
                String filePath = getRealPathFromUri(this,uri);
                Log.d("filepath",filePath);
                if (null == filePath || filePath.equals(""))
                {
                    return;
                }
       

// To do something

       //得到了檔案路徑,可以執行相應壓縮上傳操作,      
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            if (null == cursor )
            {
                return "";
            }
            if (cursor.moveToFirst())
            {
                return cursor.getString(0);
            }
        }catch (Exception e)
        {
            Log.w("resolvepic",e.getMessage());
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return "";
    }

2.回到正題,如何呼叫系統照相機呢?如下:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 指定存放拍攝照片的位置
File filePath = createImageFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
startActivityForResult(intent, 2);
------------------------------------------------------我是分隔線------------------------------------------------------
private File createImageFile() throws IOException {

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String timeStamp = format.format(System.currentTimeMillis());
    String imageFileName = "hxjysj_" + timeStamp + ".jpg";
    File image = new File(PictureUtil.getAlbumDir(this), imageFileName);
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
在onActivityResult中:
protected void onActivityResult(int requestCode, int resultCode,
                                Intent intent) 
其中intent得到的結果總是為null???
檢視相關資料發現,如果指定intent.putExtra(MediaStore.EXTRA_OUT,uri);
則intent拿到的是null.  如果沒有指定uri,則intent就會有資料的返回.
照相機會有自己的預設的儲存路徑,如果想得到圖片的路徑,則可以通過
Bitmap bitmap = (Bitmap)intent.getParcelableExtra("data");
得到bitmap再進行圖片的壓縮展示等相關的操作.
3.附Camera.java部分原始碼:
 private Bitmap createCaptureBitmap(byte[] data) {
        // This is really stupid...we just want to read the orientation in
        // the jpeg header.
        String filepath = ImageManager.getTempJpegPath();
        int degree = 0;
        if (saveDataToFile(filepath, data)) {
            degree = ImageManager.getExifOrientation(filepath);
            new File(filepath).delete();
        }

//縮放的點陣圖bitmap只有50k,如果還想得到高質量的圖片還是指定圖片路徑吧.
        // Limit to 50k pixels so we can return it in the intent.
        Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
        bitmap = Util.rotate(bitmap, degree);
        return bitmap;
    }
private void doAttach() {
        if (mPausing) {
            return;
        }


        byte[] data = mImageCapture.getLastCaptureData();


        if (mCropValue == null) {
            // First handle the no crop case -- just return the value.  If the
            // caller specifies a "save uri" then write the data to it's
            // stream. Otherwise, pass back a scaled down version of the bitmap
            // directly in the extras.
//如果指定uri就會儲存到指定的uri中,否則,通過縮放點陣圖的縮放版本
            if (mSaveUri != null) {  
//這裡說明的就是設定了指定儲存的uri地址
                OutputStream outputStream = null;
                try {
                    outputStream = mContentResolver.openOutputStream(mSaveUri);
                    outputStream.write(data);
                    outputStream.close();

      //設定了成功的返回狀態.
                    setResult(RESULT_OK);
                    finish();
                } catch (IOException ex) {
                    // ignore exception
                } finally {
                    Util.closeSilently(outputStream);
                }
            } else {
                Bitmap bitmap = createCaptureBitmap(data);
                setResult(RESULT_OK,  
                        new Intent("inline-data").putExtra("data", bitmap));
//如果沒有設定指定的儲存地址.intent就會有資料返回.
//在onActivityResult中可以通過如下方式得到一個bitmap物件再進行操作:
//Bitmap bitmap = (Bitmap)intent.getParcelableExtra("data");

                finish();
            }
        } else {
            // Save the image to a temp file and invoke the cropper
            Uri tempUri = null;
            FileOutputStream tempStream = null;
            try {
                File path = getFileStreamPath(sTempCropFilename);
                path.delete();
                tempStream = openFileOutput(sTempCropFilename, 0);
                tempStream.write(data);
                tempStream.close();
                tempUri = Uri.fromFile(path);
            } catch (FileNotFoundException ex) {
                setResult(Activity.RESULT_CANCELED);
                finish();
                return;
            } catch (IOException ex) {
                setResult(Activity.RESULT_CANCELED);
                finish();
                return;
            } finally {
                Util.closeSilently(tempStream);
            }


            Bundle newExtras = new Bundle();
            if (mCropValue.equals("circle")) {
                newExtras.putString("circleCrop", "true");
            }
            if (mSaveUri != null) {
                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
            } else {
                newExtras.putBoolean("return-data", true);
            }


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


            cropIntent.setData(tempUri);
            cropIntent.putExtras(newExtras);


            startActivityForResult(cropIntent, CROP_MSG);
        }
    }