如何在Android应用程序中取消相机

时间:2016-03-26 04:24:16

标签: android camera

enter image description here当用户点击Android模拟器中相机左侧的图标时,如何取消相机。当我打开相机并拍摄图像时,位图会发送到Image_Cropping以裁剪图像。取消相机时不会回到之前的Activity,它会转到Image_Cropping Activity.Can有人帮我解决它。

Here is my onActivityResult code

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if(requestCode == CAMERA_REQUEST)
        {

            if (requestCode == 0 && resultCode == 0){

                Toast.makeText(getApplicationContext(),"Cancel Image Capture ", Toast.LENGTH_SHORT).show();

            }else {

                onCaptureImageResult(data);

            }

        }
        if (requestCode == PROFILE_GALLERY && resultCode == RESULT_OK)
        {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            editor.putString("profile_picformat", imgDecodableString);
            editor.commit();

            Intent selfiSrc = new Intent(this, Image_Cropping.class);
            finish();
            startActivity(selfiSrc);

        }
    }


  btnCamera.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
                    String picformat = "IMG_" + 0 + "_" + s.format(new Date()) + ".png";
                    Log.e(" picformat ", " = " + picformat);

                    Intent i = new Intent(Filter_Screen.this , Image_Cropping.class );
                    startActivity(i);

                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
                    File myPath = new File(extr, picformat);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(myPath));
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);

                    Log.e("Camera", " Open");
                    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                    String imageUserProfile_path = baseDir + "/classNKK_ProfilePic/" + picformat;
                    editor.putString("profile_picformat", imageUserProfile_path);
                    editor.commit();

                   }
            });

这是我的ImageCropping类

public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.img_cropping);
        mCropImageView = (CropImageView) findViewById(R.id.CropImageView);

        dbhelper = new MyDbHelper(this);
        dbhelper.onOpen(db);

        Log.e(" In", " onCreate Method !!!!!!!!!!");
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        str_Authentication_Token = sharedPreferences.getString("strAuthentication_Token", "");
        str_UserId = sharedPreferences.getString("strUserId", "");
        str_UserName = sharedPreferences.getString("strUserName", "");
        str_UserRole = sharedPreferences.getString("strUserRole", "");
        str_LoginUserName = sharedPreferences.getString("strLogin_UserName" , "" );
        Log.e("  ", " str_Authentication_Token= " + str_Authentication_Token + " str_UserId= " + str_UserId + " str_UserName= " + str_UserName + "str_UserRole= " + str_UserRole + " str_LoginUserName= " + str_LoginUserName);
        getProfile_PicFormat = sharedPreferences.getString("profile_picformat", "");
        Log.e("getImagePath ", " getPicFormat = " + getProfile_PicFormat);

        Bitmap bmp = BitmapFactory.decodeFile(getProfile_PicFormat);
        if (savedInstanceState == null) {

            mCropImageView.setImageBitmap(bmp);
        }
        mCropImageView.setAspectRatio(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES);

        btnCropImage = (Button)findViewById(R.id.button_CropImage);
        btnCropImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mCropImageView.getCroppedImageAsync(mCropImageView.getCropShape(), 0, 0);
            }
        });

        buttonDone = (Button)findViewById(R.id.button_Done);
        buttonDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(Image_Cropping.this , Filter_Screen.class);
                finish();
                startActivity(i);
            }
        });
    }

    // Saves the state upon rotating the screen/restarting the activity
    @Override
    protected void onSaveInstanceState(@SuppressWarnings("NullableProblems") Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
        bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
    }

    // Restores the state upon rotating the screen/restarting the activity
    @Override
    protected void onRestoreInstanceState(@SuppressWarnings("NullableProblems") Bundle bundle) {
        super.onRestoreInstanceState(bundle);
        mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
        mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mCropImageView.setOnSetImageUriCompleteListener(this);
        mCropImageView.setOnGetCroppedImageCompleteListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mCropImageView.setOnSetImageUriCompleteListener(null);
        mCropImageView.setOnGetCroppedImageCompleteListener(null);
    }

    @Override
    public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
        if (error == null) {
            Toast.makeText(mCropImageView.getContext(), "Image load successful", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mCropImageView.getContext(), "Image load failed: " + error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onGetCroppedImageComplete(CropImageView view, Bitmap bitmap, Exception error) {
        if (error == null)
        {
            croppedImage = bitmap;
            int bitMapWidth = croppedImage.getWidth();
            int bitmapHeight = croppedImage.getHeight();
            Log.e("croppedImage","="+croppedImage + " bitMapWidth="+bitMapWidth + " bitmapHeight="+bitmapHeight);

            String[] finalPath = getProfile_PicFormat.split("/");
            final String split_CroppedString = finalPath[finalPath.length - 1];
            Log.e(" split_CroppedString ", " = " + split_CroppedString);

            String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
            cropped_ImagePath = "Cropped_"+split_CroppedString;
            Log.e("cropped_ImagePath "," ======>>" + cropped_ImagePath );
            File myPath = new File(extr, cropped_ImagePath);
            FileOutputStream fileOutputStream = null;
            try
            {
                fileOutputStream = new FileOutputStream(myPath);
                croppedImage.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            editor = sharedPreferences.edit();
            String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            String cropped_UserProfilepath = baseDir + "/classNKK_ProfilePic/" + cropped_ImagePath;
            editor.putString("croppedImagePath", cropped_UserProfilepath);
            editor.commit();

            String str_ProfilePic_UpLoadStatus = "0";
            db = dbhelper.getWritableDatabase();
            db.execSQL("update Inspector set ProfilePICURL = '" + cropped_ImagePath + "' , ProfilePic_UpLoadStatus='"+0+"', DownLoadStatus='1' where Inspector_Id = '" + str_UserId + "'");
            db.execSQL("update ALL_Post set ProfilePICURL = '" + cropped_ImagePath + "' , DownLoad_Status='1' where UserId = '" + str_UserId + "'");
            Log.e("Updated  ", " Succesfully !!! ImageName = " + cropped_ImagePath);

            sendPostRequest(cropped_ImagePath);
            Log.e("Cropped ", " Profile Pic  UpLoaded SuccesFully !!!!!!!!!!!!!! ");

            String delete_cropped_UserProfilepath = baseDir + "/classNKK_ProfilePic/" + split_CroppedString;
            File file= new File(delete_cropped_UserProfilepath);
            if(file.exists())
            {
                file.delete();
                Log.e("Original "," File is deleted !!!");
            }

            Intent i = new Intent(Image_Cropping.this , Filter_Screen.class);
            startActivity(i);
            finish();


        } else {
            Toast.makeText(mCropImageView.getContext(), "Image Crop failed: " + error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private Uri getCaptureImageOutputUri() {
        Uri outputFileUri = null;
        File getImage = getExternalCacheDir();
        if (getImage != null) {
            outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
        }
        return outputFileUri;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri imageUri = getPickImageResultUri(data);
            ((CropImageView) findViewById(R.id.CropImageView)).setImageUriAsync(imageUri);
        }
    }

    public Uri getPickImageResultUri(Intent data) {
        boolean isCamera = true;
        if (data != null) {
            String action = data.getAction();
            isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
        }
        return isCamera ? getCaptureImageOutputUri() : data.getData();
    }}

先谢谢。

1 个答案:

答案 0 :(得分:0)

现在就复制一下吧。  Imagecropping clsaa没有任何变化。

    btnCamera.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
                String picformat = "IMG_" + 0 + "_" + s.format(new Date()) + ".png";
                Log.e(" picformat ", " = " + picformat);

                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
                File myPath = new File(extr, picformat);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(myPath));
                startActivityForResult(cameraIntent, CAMERA_REQUEST);

                Log.e("Camera", " Open");
                String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                String imageUserProfile_path = baseDir + "/classNKK_ProfilePic/" + picformat;
                editor.putString("profile_picformat", imageUserProfile_path);
                editor.commit();

               }
        });




 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

   if(requestCode == CAMERA_REQUEST)
    {

        if (requestCode == 0 && resultCode == 0){

            Toast.makeText(getApplicationContext(),"Canceling Image Capture ", Toast.LENGTH_SHORT).show();

        }else {

            onCaptureImageResult(data);

        }

    }
   if (requestCode == PROFILE_GALLERY && resultCode == RESULT_OK)
    {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String imgDecodableString = cursor.getString(columnIndex);
        cursor.close();

        editor.putString("profile_picformat", imgDecodableString);
        editor.commit();

        Intent selfiSrc = new Intent(this, Image_Cropping.class);
        finish();
        startActivity(selfiSrc);

     }
}

 private void onCaptureImageResult(Intent data) {

  Intent selfiSrc = new Intent(this, Image_Cropping.class);
        startActivity(selfiSrc);
         finish();
  }