Ejemplo n.º 1
0
  @Override
  public void send(Map<String, Object> params, final IMethodResult result) {
    Intent intent = makeIntent(params);
    Object type = params.get(HK_INTENT_TYPE);
    if (BROADCAST.equals(type)) {
      Object permissionObj = params.get(HK_PERMISSION);
      String permission = null;
      if (permissionObj != null) {
        if (String.class.isInstance(permissionObj)) {
          permission = (String) permissionObj;
        } else {
          result.setArgError("Wrong intent permission: " + permissionObj);
          return;
        }
      }
      Logger.T(TAG, "Send broadcast: " + intent);
      ContextFactory.getAppContext().sendBroadcast(intent, permission);
    } else if (START_ACTIVITY.equals(type)) {
      if (result.hasCallback()) {
        int request;
        synchronized (localMethodResults) {
          request = RhoExtManager.getInstance().getActivityResultNextRequestCode(this);
          final Integer finalKey = Integer.valueOf(request);
          Map.Entry<Integer, IMethodResult> entry =
              new Map.Entry<Integer, IMethodResult>() {
                Integer key = finalKey;
                IMethodResult value = result;

                @Override
                public Integer getKey() {
                  return key;
                }

                @Override
                public IMethodResult getValue() {
                  return value;
                }

                @Override
                public IMethodResult setValue(IMethodResult v) {
                  return result;
                }
              };
          localMethodResults.add(entry);
        }
        RhodesActivity.safeGetInstance().startActivityForResult(intent, request);
        Logger.T(TAG, "Start activity for result: " + intent);
      } else {
        Logger.T(TAG, "Start activity: " + intent);
        ContextFactory.getUiContext().startActivity(intent);
      }
    } else if (START_SERVICE.equals(type)) {
      Logger.T(TAG, "Start service: " + intent);
      ContextFactory.getContext().startService(intent);
    } else {
      result.setArgError("Wrong intent type: " + type);
    }
  }
Ejemplo n.º 2
0
  private Intent makeIntent(Map<String, Object> params) {
    Intent intent = new Intent();

    Object actionObj = params.get(HK_ACTION);
    Object categoriesObj = params.get(HK_CATEGORIES);
    Object appNameObj = params.get(HK_APP_NAME);
    Object targetClassObj = params.get(HK_TARGET_CLASS);
    Object uriObj = params.get(HK_URI);
    Object mimeObj = params.get(HK_MIME_TYPE);
    Object extrasObj = params.get(HK_DATA);

    String action = null;
    List<String> categories = null;
    String appName = null;
    String targetClass = null;
    String uri = null;
    String mime = null;
    Map<String, Object> extras = null;

    // --- Check param types ---

    if (actionObj != null) {
      if (!String.class.isInstance(actionObj)) {
        throw new RuntimeException("Wrong intent action: " + actionObj.toString());
      }
      action = constant((String) actionObj);
    }

    if (categoriesObj != null) {
      if (!List.class.isInstance(categoriesObj)) {
        throw new RuntimeException("Wrong intent categories: " + categoriesObj.toString());
      }
      categories = new ArrayList<String>();
      for (String cat : (List<String>) categoriesObj) {
        categories.add(constant(cat));
      }
    }

    if (appNameObj != null) {
      if (!String.class.isInstance(appNameObj)) {
        throw new RuntimeException("Wrong intent appName: " + appNameObj.toString());
      }
      appName = (String) appNameObj;
    }

    if (targetClassObj != null) {
      if (!String.class.isInstance(targetClassObj)) {
        throw new RuntimeException("Wrong intent targetClass: " + targetClassObj.toString());
      }
      targetClass = (String) targetClassObj;
    }

    if (uriObj != null) {
      if (!String.class.isInstance(uriObj)) {
        throw new RuntimeException("Wrong intent uri: " + uriObj.toString());
      }
      uri = (String) uriObj;
    }

    if (mimeObj != null) {
      if (!String.class.isInstance(mimeObj)) {
        throw new RuntimeException("Wrong intent mimeType: " + mimeObj.toString());
      }
      mime = (String) mimeObj;
    }

    if (extrasObj != null) {
      if (!Map.class.isInstance(extrasObj)) {
        throw new RuntimeException("Wrong intent data: " + extrasObj.toString());
      }
      extras = (Map<String, Object>) extrasObj;
    }

    // --- Fill intent fields ---

    if (action != null) {
      intent.setAction(action);
    }

    if (categories != null) {
      for (String category : categories) {
        intent.addCategory(category);
        if (intent.toString().contains(" xxx ") && isTablet(ContextFactory.getContext())) {
          intent.removeCategory(category);
        }
      }
    }

    if (targetClass != null) {
      if (appName == null) {
        throw new RuntimeException("Wrong intent appName: cannot be nil if targetClass is set");
      }
      intent.setClassName(appName, targetClass);
    } else if (appName != null) {
      intent.setPackage(appName);
    }

    if (uri != null) {
      Uri data = Uri.parse(uri);
      if (mime == null) {
        intent.setData(data);
      } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
          intent.setDataAndTypeAndNormalize(data, mime);
        } else {
          intent.setDataAndType(data, mime);
        }
      }
      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_FORWARD_RESULT);
    } else if (mime != null) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        intent.setTypeAndNormalize(mime);
      } else {
        intent.setType(mime);
      }
    }

    if (extras != null) {
      for (Map.Entry<String, Object> entry : extras.entrySet()) {

        if (String.class.isInstance(entry.getValue())) {
          intent.putExtra(constant(entry.getKey()), (String) entry.getValue());
        } else if (Boolean.class.isInstance(entry.getValue())) {
          intent.putExtra(constant(entry.getKey()), ((Boolean) entry.getValue()).booleanValue());
        } else if (Integer.class.isInstance(entry.getValue())) {
          intent.putExtra(constant(entry.getKey()), ((Integer) entry.getValue()).intValue());
        } else if (Double.class.isInstance(entry.getValue())) {
          intent.putExtra(constant(entry.getKey()), ((Double) entry.getValue()).doubleValue());
        } else if (ArrayList.class.isInstance(entry.getValue())) {
          ArrayList list = (ArrayList) entry.getValue();
          if (list.size() > 0) {
            if (String.class.isInstance(list.get(0))) {
              intent.putExtra(constant(entry.getKey()), list.toArray(new String[list.size()]));
            } else if (Integer.class.isInstance(list.get(0))) {
              intent.putExtra(constant(entry.getKey()), list.toArray(new Integer[list.size()]));
            } else {
              throw new RuntimeException(
                  "Wrong intent data: array of "
                      + list.get(0).getClass().getName()
                      + " is not supported as value");
            }
          } else {
            intent.putExtra(constant(entry.getKey()), new String[0]);
          }
        } else {
          throw new RuntimeException(
              "Wrong intent data: "
                  + entry.getValue().getClass().getName()
                  + " is not supported as value");
        }
      }
    }

    return intent;
  }
Ejemplo n.º 3
0
  @Override
  public void takePicture(Map<String, String> propertyMap, IMethodResult result) {
    Logger.T(TAG, "takePicture");
    try {
      Map<String, String> actualPropertyMap = new HashMap<String, String>();
      actualPropertyMap.putAll(getPropertiesMap());
      actualPropertyMap.putAll(propertyMap);
      setActualPropertyMap(actualPropertyMap);

      String outputFormat = actualPropertyMap.get("outputFormat");
      String filePath = null;
      if (!actualPropertyMap.containsKey("fileName")) {
        filePath =
            "/sdcard/DCIM/Camera/IMG_"
                + dateFormat.format(new Date(System.currentTimeMillis()))
                + ".jpg";
      } else {
        filePath = actualPropertyMap.get("fileName");
      }
      if (outputFormat.equalsIgnoreCase("image")) {
        filePath = actualPropertyMap.get("fileName") + ".jpg";
        Logger.T(TAG, "outputFormat: " + outputFormat + ", path: " + filePath);
      } else if (outputFormat.equalsIgnoreCase("dataUri")) {
        Logger.T(TAG, "outputFormat: " + outputFormat);
      } else {
        throw new RuntimeException("Unknown 'outputFormat' value: " + outputFormat);
      }

      Intent intent = null;
      if (Boolean.parseBoolean(actualPropertyMap.get("useSystemViewfinder"))) {
        if (outputFormat.equalsIgnoreCase("image")) {
          values = new ContentValues();
          fileUri =
              RhodesActivity.getContext()
                  .getContentResolver()
                  .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
          intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          actualPropertyMap.put("captureUri", fileUri.toString());
          propertyMap.put("dataURI", "");
          // intent is null with MediaStore.EXTRA_OUTPUT so adding fileuri to map and get it with
          // same key
          // if instead of MediaStore.EXTRA_OUTPUT any other key is used then the bitmap is null
          // though the file is getting created
          intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        } else if (outputFormat.equalsIgnoreCase("dataUri")) {

        }
      } else {
        intent = new Intent(ContextFactory.getUiContext(), CameraActivity.class);
        intent.putExtra(CameraExtension.INTENT_EXTRA_PREFIX + "CAMERA_ID", getId());
      }
      ((CameraFactory) CameraFactorySingleton.getInstance())
          .getRhoListener()
          .setMethodResult(result);
      ((CameraFactory) CameraFactorySingleton.getInstance())
          .getRhoListener()
          .setActualPropertyMap(actualPropertyMap);

      RhodesActivity.safeGetInstance()
          .startActivityForResult(
              intent,
              RhoExtManager.getInstance()
                  .getActivityResultNextRequestCode(CameraRhoListener.getInstance()));
    } catch (RuntimeException e) {
      Logger.E(TAG, e);
      result.setError(e.getMessage());
    }
  }
Ejemplo n.º 4
0
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
      Intent intent = new Intent();
      OutputStream stream = null;
      try {

        final Map<String, String> propertyMap = getActualPropertyMap();
        if (propertyMap == null) {
          throw new RuntimeException("Camera property map is undefined");
        }

        String outputFormat = propertyMap.get("outputFormat");
        if (propertyMap.get("deprecated") == null
            || propertyMap.get("deprecated").equalsIgnoreCase("false")) {
          propertyMap.put("deprecated", "false");
          deprecated_take_pic = false;
        } else deprecated_take_pic = true;
        if (propertyMap.containsKey("captureSound")) {
          Runnable music =
              new Runnable() {
                public void run() {
                  playMusic(propertyMap.get("captureSound"));
                }
              };
          ExecutorService exec = Executors.newSingleThreadExecutor();
          exec.submit(music);
        }

        String filePath = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss");
        if (!propertyMap.containsKey("fileName")) {
          filePath =
              "/sdcard/DCIM/Camera/IMG_" + dateFormat.format(new Date(System.currentTimeMillis()));
          userFilePath = filePath;
        } else {
          filePath = propertyMap.get("fileName");
          userFilePath = filePath;
          if (filePath.contains("\\")) {
            intent.putExtra("error", "Invalid file path");
          }
        }
        Uri resultUri = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        Matrix m = new Matrix();
        android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(getCameraIndex(), info);
        if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT
            && OrientationListnerService.mRotation == 90) {
          m.postRotate(270);
        } else if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT
            && OrientationListnerService.mRotation == 270) {
          m.postRotate(90);
        } else {
          m.postRotate(OrientationListnerService.mRotation);
        }
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
        if (outputFormat.equalsIgnoreCase("dataUri")) {
          Logger.T(TAG, "outputFormat: " + outputFormat);
          //    filePath = getTemporaryPath(filePath)+ ".jpg";
          if (Boolean.parseBoolean(propertyMap.get("saveToDeviceGallery"))) {
            ContentResolver contentResolver = ContextFactory.getContext().getContentResolver();
            Logger.T(TAG, "Image size: " + bitmap.getWidth() + "X" + bitmap.getHeight());
            propertyMap.put("DeviceGallery_Key", "DeviceGallery_Value");
            String strUri = null;
            if (!propertyMap.containsKey("fileName")) {
              strUri =
                  MediaStore.Images.Media.insertImage(
                      contentResolver,
                      bitmap,
                      "IMG_" + dateFormat.format(new Date(System.currentTimeMillis())),
                      "Camera");
            } else {
              strUri =
                  MediaStore.Images.Media.insertImage(
                      contentResolver,
                      bitmap,
                      new File(propertyMap.get("fileName")).getName(),
                      "Camera");
            }
            if (strUri != null) {
              resultUri = Uri.parse(strUri);
            } else {
              throw new RuntimeException("Failed to save camera image to Gallery");
            }
          } else {
            if (userFilePath.contains("sdcard")) {

              Boolean isSDPresent =
                  android.os.Environment.getExternalStorageState()
                      .equals(android.os.Environment.MEDIA_MOUNTED);

              if (isSDPresent) {
                byte[] byteArray = null;
                int lastIndex = userFilePath.lastIndexOf("/");

                String subfolderName = userFilePath.replaceAll("/sdcard", "");
                String folderName =
                    subfolderName.substring(
                        subfolderName.indexOf("/") + 1, subfolderName.lastIndexOf("/"));

                String file_name = userFilePath.substring(lastIndex + 1, userFilePath.length());

                File directory =
                    new File(
                        Environment.getExternalStorageDirectory() + File.separator + folderName);
                boolean flag = directory.mkdirs();

                stream = new FileOutputStream(directory + File.separator + file_name + ".jpg");
                resultUri = Uri.fromFile(new File(directory + File.separator + file_name + ".jpg"));
                if (bitmap != null) {
                  ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytestream);
                  byteArray = bytestream.toByteArray();
                  stream.write(byteArray);
                  stream.flush();
                  stream.close();
                }
              }
            } else {
              stream = new FileOutputStream(filePath);
              resultUri = Uri.fromFile(new File(filePath));
              byte[] byteArray = null;
              if (bitmap != null) {
                ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytestream);
                byteArray = bytestream.toByteArray();
                stream.write(byteArray);
                stream.flush();
                stream.close();
              }
            }
            // CameraRhoListener.getInstance().copyImgAsUserChoice(filePath);
          }
          byte[] byteArray = null;
          stream = new FileOutputStream(filePath);
          if (bitmap != null) {
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytestream);
            byteArray = bytestream.toByteArray();
            stream.write(byteArray);
            stream.flush();
            stream.close();
          }
          StringBuilder dataBuilder = new StringBuilder();
          dataBuilder.append("data:image/jpeg;base64,");
          dataBuilder.append(Base64.encodeToString(byteArray, false));
          propertyMap.put("captureUri", dataBuilder.toString());
          propertyMap.put("dataURI", "datauri_value");
          Logger.T(TAG, dataBuilder.toString());
          intent.putExtra("IMAGE_WIDTH", bitmap.getWidth());
          intent.putExtra("IMAGE_HEIGHT", bitmap.getHeight());
          mPreviewActivity.setResult(Activity.RESULT_OK, intent);
        } else if (outputFormat.equalsIgnoreCase("image")) {
          //    filePath = getTemporaryPath(filePath)+ ".jpg";
          Logger.T(TAG, "outputFormat: " + outputFormat + ", path: " + filePath);
          if (Boolean.parseBoolean(propertyMap.get("saveToDeviceGallery"))) {
            ContentResolver contentResolver = ContextFactory.getContext().getContentResolver();
            Logger.T(TAG, "Image size: " + bitmap.getWidth() + "X" + bitmap.getHeight());
            propertyMap.put("DeviceGallery_Key", "DeviceGallery_Value");
            String strUri = null;
            if (!propertyMap.containsKey("fileName"))
              strUri =
                  MediaStore.Images.Media.insertImage(
                      contentResolver,
                      bitmap,
                      "IMG_" + dateFormat.format(new Date(System.currentTimeMillis())),
                      "Camera");
            else
              strUri =
                  MediaStore.Images.Media.insertImage(
                      contentResolver,
                      bitmap,
                      new File(propertyMap.get("fileName")).getName(),
                      "Camera");
            if (strUri != null) {
              resultUri = Uri.parse(strUri);
            } else {
              throw new RuntimeException("Failed to save camera image to Gallery");
            }
          } else {
            stream = new FileOutputStream(filePath);
            resultUri = Uri.fromFile(new File(filePath));
            byte[] byteArray = null;
            if (bitmap != null) {
              ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytestream);
              byteArray = bytestream.toByteArray();
              stream.write(byteArray);
              stream.flush();
              stream.close();
            }
          }

          intent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri);
          intent.putExtra("IMAGE_WIDTH", bitmap.getWidth());
          intent.putExtra("IMAGE_HEIGHT", bitmap.getHeight());
          mPreviewActivity.setResult(Activity.RESULT_OK, intent);
        }

      } catch (Throwable e) {
        Logger.E(TAG, e);
        if (stream != null) {
          try {
            stream.close();
          } catch (Throwable e1) {
            // Do nothing
          }
        }
        intent.putExtra("error", e.getMessage());
        mPreviewActivity.setResult(Activity.RESULT_CANCELED, intent);
      }
      if (bitmap != null) {
        bitmap.recycle();
        bitmap = null;
        System.gc();
      }
      mPreviewActivity.finish();
    }