Example usage for android.net Uri getPath

List of usage examples for android.net Uri getPath

Introduction

In this page you can find the example usage for android.net Uri getPath.

Prototype

@Nullable
public abstract String getPath();

Source Link

Document

Gets the decoded path.

Usage

From source file:com.sebible.cordova.videosnapshot.VideoSnapshot.java

/**
 * Take snapshots of a video file// w w  w. j a  va 2 s  . co  m
 *
 * @param source path of the file
 * @param count of snapshots that are gonna be taken
 */
private void snapshot(final JSONObject options) {
    final CallbackContext context = this.callbackContext;
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                int count = options.optInt("count", 1);
                int countPerMinute = options.optInt("countPerMinute", 0);
                int quality = options.optInt("quality", 90);
                String source = options.optString("source", "");
                Boolean timestamp = options.optBoolean("timeStamp", true);
                String prefix = options.optString("prefix", "");
                int textSize = options.optInt("textSize", 48);

                if (source.isEmpty()) {
                    throw new Exception("No source provided");
                }

                JSONObject obj = new JSONObject();
                obj.put("result", false);
                JSONArray results = new JSONArray();

                Log.i("snapshot", "Got source: " + source);
                Uri p = Uri.parse(source);
                String filename = p.getLastPathSegment();

                FileInputStream in = new FileInputStream(new File(p.getPath()));
                retriever.setDataSource(in.getFD());
                String tmp = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                long duration = Long.parseLong(tmp);
                if (countPerMinute > 0) {
                    count = (int) (countPerMinute * duration / (60 * 1000));
                }
                if (count < 1) {
                    count = 1;
                }
                long delta = duration / (count + 1); // Start at duration * 1 and ends at duration * count
                if (delta < 1000) { // min 1s
                    delta = 1000;
                }

                Log.i("snapshot", "duration:" + duration + " delta:" + delta);

                File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                for (int i = 1; delta * i < duration && i <= count; i++) {
                    String filename2 = filename.replace('.', '_') + "-snapshot" + i + ".jpg";
                    File dest = new File(storage, filename2);
                    if (!storage.exists() && !storage.mkdirs()) {
                        throw new Exception("Unable to access storage:" + storage.getPath());
                    }
                    FileOutputStream out = new FileOutputStream(dest);
                    Bitmap bm = retriever.getFrameAtTime(i * delta * 1000);
                    if (timestamp) {
                        drawTimestamp(bm, prefix, delta * i, textSize);
                    }
                    bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
                    out.flush();
                    out.close();
                    results.put(dest.getAbsolutePath());
                }

                obj.put("result", true);
                obj.put("snapshots", results);
                context.success(obj);
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e("snapshot", "Exception:", ex);
                fail("Exception: " + ex.toString());
            } finally {
                try {
                    retriever.release();
                } catch (RuntimeException ex) {
                }
            }
        }
    });
}

From source file:camera.AnotherCamera.java

/**
 * Start the camera by dispatching a camera intent.
 *///w  ww .  ja v  a  2 s.c  o  m
protected void dispatchTakePictureIntent() {

    // Check if there is a camera.
    Context context = getActivity();
    PackageManager packageManager = context.getPackageManager();
    if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false) {
        Toast.makeText(getActivity(), "This device does not have a camera.", Toast.LENGTH_SHORT).show();
        return;
    }

    // Camera exists? Then proceed...
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Ensure that there's a camera activity to handle the intent
    CameraActivity activity = (CameraActivity) getActivity();
    if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
        // Create the File where the photo should go.
        // If you don't do this, you may get a crash in some devices.
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Toast toast = Toast.makeText(activity, "There was a problem saving the photo...",
                    Toast.LENGTH_SHORT);
            toast.show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri fileUri = Uri.fromFile(photoFile);
            activity.setCapturedImageURI(fileUri);
            activity.setCurrentPhotoPath(fileUri.getPath());
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, activity.getCapturedImageURI());
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

From source file:com.dena.app.bootloadhid.MainFragment.java

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (Activity.RESULT_OK == resultCode && null != data) {
        Uri uri = data.getData();
        if (null != uri && "file".equalsIgnoreCase(uri.getScheme())) {
            setFilePath(uri.getPath());
        }//from   ww w.  j  av a2 s .c o  m
    }
}

From source file:com.codebutler.farebot.activities.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {//  w  w  w  .j  av a  2s  .  c  o  m
        if (resultCode == RESULT_OK && requestCode == SELECT_FILE) {
            Uri uri = data.getData();
            String xml = org.apache.commons.io.FileUtils.readFileToString(new File(uri.getPath()));
            onCardsImported(ExportHelper.importCardsXml(this, xml));
        }
    } catch (Exception ex) {
        Utils.showError(this, ex);
    }
}

From source file:mobisocial.musubi.util.UriImage.java

private void initFromFile(Context context, Uri uri) {
    mPath = uri.getPath();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String extension = MimeTypeMap.getFileExtensionFromUrl(mPath);
    if (TextUtils.isEmpty(extension)) {
        // getMimeTypeFromExtension() doesn't handle spaces in filenames nor can it handle
        // urlEncoded strings. Let's try one last time at finding the extension.
        int dotPos = mPath.lastIndexOf('.');
        if (0 <= dotPos) {
            extension = mPath.substring(dotPos + 1);
        }/*from   w w  w  . j av  a 2  s.c  o m*/
    }
    mContentType = mimeTypeMap.getMimeTypeFromExtension(extension);
    // It's ok if mContentType is null. Eventually we'll show a toast telling the
    // user the picture couldn't be attached.
}

From source file:cgeo.geocaching.connector.oc.OCApiConnector.java

/**
 * get the OC1234 geocode from an internal cache id, for URLs like host.tld/viewcache.php?cacheid
 *//*www .  j  a va2 s.  c  om*/
@Nullable
protected String getGeocodeFromCacheId(final String url, final String host) {
    final Uri uri = Uri.parse(url);
    if (!StringUtils.containsIgnoreCase(uri.getHost(), host)) {
        return null;
    }

    // host.tld/viewcache.php?cacheid=cacheid
    final String id = uri.getPath().startsWith("/viewcache.php") ? uri.getQueryParameter("cacheid") : "";
    if (StringUtils.isNotBlank(id)) {
        final String geocode = Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() throws Exception {
                final String normalizedUrl = StringUtils.replaceIgnoreCase(url, getShortHost(), getShortHost());
                return OkapiClient.getGeocodeByUrl(OCApiConnector.this, normalizedUrl);
            }
        }).subscribeOn(AndroidRxUtils.networkScheduler).blockingGet();

        if (geocode != null && canHandle(geocode)) {
            return geocode;
        }
    }
    return null;
}

From source file:com.gelecekonline.android.uploadornek.MainActivity.java

/**
 * Secilen resim bu methoda gelir/*w  w w  .  jav a 2s  .  com*/
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        Uri selectedImageUri = data.getData();
        String filePath = null;

        try {
            String fileManagerString = selectedImageUri.getPath();

            String selectedImagePath = getPath(selectedImageUri);

            if (selectedImagePath != null) {
                filePath = selectedImagePath;
            } else if (fileManagerString != null) {
                filePath = fileManagerString;
            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.unknown_path), Toast.LENGTH_LONG)
                        .show();
            }

            if (filePath != null) {
                decodeFile(filePath);
                dosyaAdi = FilenameUtils.getName(filePath);
            } else {
                bitmap = null;
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), getString(R.string.internal_error), Toast.LENGTH_LONG)
                    .show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
    }
}

From source file:com.silverpop.engage.deeplinking.EngageDeepLinkManager.java

private void routeUsingUrl(Uri deeplink) throws JSONException {
    // base case//from   ww  w  .  j  a  va  2  s .c  o  m
    if (TextUtils.isEmpty(deeplink.getHost()) && (TextUtils.isEmpty(deeplink.getPath()))) {
        MDLLog.e("MobileDeepLinking", "No Routes Match.");
        routeToDefault(deeplink);
        return;
    }

    if (config.getRoutes() != null) {
        Iterator<String> keys = config.getRoutes().keys();
        while (keys.hasNext()) {
            String route = keys.next();
            JSONObject routeOptions = (JSONObject) config.getRoutes().get(route);
            try {
                Map<String, String> routeParameters = new HashMap<String, String>();
                routeParameters = DeeplinkMatcher.match(route, routeOptions, routeParameters, deeplink);
                if (routeParameters != null) {
                    handleRoute(routeOptions, routeParameters, deeplink);
                    return;
                }
            } catch (JSONException e) {
                MDLLog.e("MobileDeepLinking", "Error parsing JSON!", e);
                break;
            } catch (Exception e) {
                MDLLog.e("MobileDeepLinking", "Error matching and handling route", e);
                break;
            }
        }
    }

    // deeplink trimmer
    routeUsingUrl(trimDeeplink(deeplink));
}

From source file:com.remobile.file.AssetFilesystem.java

@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
    if (!"file".equals(inputURL.getScheme())) {
        return null;
    }//from w w w. j a  v a  2  s .  co  m
    File f = new File(inputURL.getPath());
    // Removes and duplicate /s (e.g. file:///a//b/c)
    Uri resolvedUri = Uri.fromFile(f);
    String rootUriNoTrailingSlash = rootUri.getEncodedPath();
    rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
    if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
        return null;
    }
    String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
    // Strip leading slash
    if (!subPath.isEmpty()) {
        subPath = subPath.substring(1);
    }
    Uri.Builder b = new Uri.Builder().scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL).authority("localhost")
            .path(name);
    if (!subPath.isEmpty()) {
        b.appendEncodedPath(subPath);
    }
    if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
        // Add trailing / for directories.
        b.appendEncodedPath("");
    }
    return LocalFilesystemURL.parse(b.build());
}

From source file:com.nogago.android.tracks.ImportActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();/*from   w  w w .jav a  2 s. co m*/
    importAll = intent.getBooleanExtra(EXTRA_IMPORT_ALL, false);
    if (importAll) {
        path = FileUtils.buildExternalDirectoryPath("gpx");
    } else {
        String action = intent.getAction();
        if (!(Intent.ACTION_ATTACH_DATA.equals(action) || Intent.ACTION_VIEW.equals(action))) {
            Log.d(TAG, "Invalid action: " + intent);
            finish();
            return;
        }

        Uri data = intent.getData();
        if (!UriUtils.isFileUri(data)) {
            Log.d(TAG, "Invalid data: " + intent);
            finish();
            return;
        }
        path = data.getPath();
    }

    Object retained = getLastNonConfigurationInstance();
    if (retained instanceof ImportAsyncTask) {
        importAsyncTask = (ImportAsyncTask) retained;
        importAsyncTask.setActivity(this);
    } else {
        importAsyncTask = new ImportAsyncTask(this, importAll, path);
        importAsyncTask.execute();
    }
}