Как отменить камеру в приложении AndroidAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как отменить камеру в приложении Android

Сообщение Anonymous »


Как отменить камеру, когда пользователь будет нажимать на значок левой стороны на камере в эмуляторе Android. Когда я открываю камеру и захватываю изображение растровое изображение, отправляется на image_cropping для обрезки изображения. При отмене камеры она не возвращается к предыдущей деятельности, она переходит к Image_cropping Activity. Может ли кто-нибудь помочь мне решить.

Код: Выделить всё

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();

}
});
< /code>
Это мой класс Imagecropping < /p>
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();
}
заранее спасибо.


Подробнее здесь: https://stackoverflow.com/questions/362 ... pplication
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»