@Override
 protected void onDestroy() {
   if (storeImageTask != null) storeImageTask.cancel(true);
   super.onDestroy();
 }
  protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
      case REQ_CODE_CROP_IMAGE:

        // The photo is cropped. Kick off the store image task to save it to the
        // appropriate contact.

        if (resultCode == RESULT_OK) {
          storeImageTask = new StoreImageTask();
          storeImageTask.execute();
        } else {
          cropTemp.delete();
        }
        break;

      case REQ_CODE_PICK_IMAGE:
        if (resultCode != RESULT_OK) return;

        // The image is picked by the user. Query its MIME type.

        Uri selectedImage = imageReturnedIntent.getData();

        Cursor cursor =
            getContentResolver()
                .query(selectedImage, new String[] {Media.MIME_TYPE}, null, null, null);

        if (cursor == null) {
          Toast.makeText(
                  this, getResources().getString(R.string.something_went_wrong), Toast.LENGTH_LONG)
              .show();
          return;
        }

        String mimeType = "";

        try {
          cursor.moveToFirst();
          mimeType = cursor.getString(cursor.getColumnIndex(Media.MIME_TYPE));
        } finally {
          cursor.close();
        }

        // Currently, we only accept PNG and JPEG images. Puke on anything else.

        if (!"image/jpeg".equals(mimeType) && !"image/png".equals(mimeType)) {
          Toast.makeText(
                  this, getResources().getString(R.string.only_image_allowed), Toast.LENGTH_LONG)
              .show();
          return;
        }

        // Create a temporary file to pass to CropPhotoActivity for saving the
        // cropped photo.

        try {
          cropTemp = File.createTempFile("croptemp-", "", getCacheDir());
        } catch (IOException e) {
          Toast.makeText(
                  this, getResources().getString(R.string.something_went_wrong), Toast.LENGTH_LONG)
              .show();
          return;
        }

        // Fire up the cropper.

        Intent intent = new Intent(this, CropPhotoActivity.class);
        intent.setData(selectedImage);
        intent.putExtra("wratio", 1.0f);
        intent.putExtra("hratio", 1.0f);
        intent.putExtra("maxwidth", getResources().getInteger(R.integer.config_max_photo_dim));
        intent.putExtra("maxheight", getResources().getInteger(R.integer.config_max_photo_dim));
        // intent.putExtra("quality", 0);
        intent.putExtra("out", Uri.fromFile(cropTemp));
        startActivityForResult(intent, REQ_CODE_CROP_IMAGE);
    }
  }