Example usage for android.net Uri getLastPathSegment

List of usage examples for android.net Uri getLastPathSegment

Introduction

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

Prototype

@Nullable
public abstract String getLastPathSegment();

Source Link

Document

Gets the decoded last segment in the path.

Usage

From source file:com.amaze.filemanager.fragments.ZipViewer.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    s = getArguments().getString("path");
    Uri uri = Uri.parse(s);
    f = new File(uri.getPath());
    mToolbarContainer = getActivity().findViewById(R.id.lin);
    mToolbarContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override//w  w w . ja  va 2 s.  co m
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (stopAnims) {
                if ((!rarAdapter.stoppedAnimation)) {
                    stopAnim();
                }
                rarAdapter.stoppedAnimation = true;

            }
            stopAnims = false;
            return false;
        }
    });
    hidemode = Sp.getInt("hidemode", 0);
    listView.setVisibility(View.VISIBLE);
    mLayoutManager = new LinearLayoutManager(getActivity());
    listView.setLayoutManager(mLayoutManager);
    res = getResources();
    mainActivity.supportInvalidateOptionsMenu();
    if (mainActivity.theme1 == 1)
        rootView.setBackgroundColor(getResources().getColor(R.color.holo_dark_background));
    else
        listView.setBackgroundColor(getResources().getColor(android.R.color.background_light));

    gobackitem = Sp.getBoolean("goBack_checkbox", false);
    coloriseIcons = Sp.getBoolean("coloriseIcons", true);
    Calendar calendar = Calendar.getInstance();
    showSize = Sp.getBoolean("showFileSize", false);
    showLastModified = Sp.getBoolean("showLastModified", true);
    showDividers = Sp.getBoolean("showDividers", true);
    year = ("" + calendar.get(Calendar.YEAR)).substring(2, 4);
    skin = PreferenceUtils.getPrimaryColorString(Sp);
    iconskin = PreferenceUtils.getFolderColorString(Sp);
    mainActivity.findViewById(R.id.buttonbarframe).setBackgroundColor(Color.parseColor(skin));

    files = new ArrayList<>();
    if (savedInstanceState == null && f != null) {
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(null);
        } else {
            openmode = 0;
            SetupZip(null);
        }
    } else {
        f = new File(savedInstanceState.getString("file"));
        s = savedInstanceState.getString("uri");
        uri = Uri.parse(s);
        f = new File(uri.getPath());
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(savedInstanceState);
        } else {
            openmode = 0;
            SetupZip(savedInstanceState);
        }

    }
    String fileName = null;
    try {
        if (uri.getScheme().equals("file")) {
            fileName = uri.getLastPathSegment();
        } else {
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri,
                        new String[] { MediaStore.Images.ImageColumns.DISPLAY_NAME }, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor
                            .getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
                }
            } finally {

                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (fileName == null || fileName.trim().length() == 0)
        fileName = f.getName();
    try {
        mainActivity.setActionBarTitle(fileName);
    } catch (Exception e) {
        mainActivity.setActionBarTitle(getResources().getString(R.string.zip_viewer));
    }
    mainActivity.supportInvalidateOptionsMenu();
    mToolbarHeight = getToolbarHeight(getActivity());
    paddingTop = (mToolbarHeight) + dpToPx(72);
    mToolbarContainer.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    paddingTop = mToolbarContainer.getHeight();
                    mToolbarHeight = mainActivity.toolbar.getHeight();

                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }

            });

}

From source file:com.pavlospt.rxfile.RxFile.java

private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data,
        final int requiredWidth, final int requiredHeight, final int kind) {
    return Observable.fromCallable(new Func0<Bitmap>() {
        @Override/*from  w ww  .j  av a 2  s  .  c o m*/
        public Bitmap call() {
            Bitmap bitmap = null;
            ParcelFileDescriptor parcelFileDescriptor;
            final BitmapFactory.Options options = new BitmapFactory.Options();
            if (requiredWidth > 0 && requiredHeight > 0) {
                options.inJustDecodeBounds = true;
                options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);
                options.inJustDecodeBounds = false;
            }
            if (!isMediaUri(data)) {
                logDebug("Not a media uri:" + data);
                if (isGoogleDriveDocument(data)) {
                    logDebug("Google Drive Uri:" + data);
                    DocumentFile file = DocumentFile.fromSingleUri(context, data);
                    if (file.getType().startsWith(Constants.IMAGE_TYPE)
                            || file.getType().startsWith(Constants.VIDEO_TYPE)) {
                        logDebug("Google Drive Uri:" + data + " (Video or Image)");
                        try {
                            parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                    Constants.READ_MODE);
                            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                            bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                            parcelFileDescriptor.close();
                            return bitmap;
                        } catch (IOException e) {
                            logError("Exception:" + e.getMessage() + " line: 209");
                            e.printStackTrace();
                        }
                    }
                } else if (data.getScheme().equals(Constants.FILE)) {
                    logDebug("Dropbox or other DocumentsProvider Uri:" + data);
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        logError("Exception:" + e.getMessage() + " line: 223");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
                                Constants.READ_MODE);
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        parcelFileDescriptor.close();
                        return bitmap;
                    } catch (IOException e) {
                        logError("Exception:" + e.getMessage() + " line: 235");
                        e.printStackTrace();
                    }
                }
            } else {
                logDebug("Uri for thumbnail:" + data);
                String[] parts = data.getLastPathSegment().split(":");
                String fileId = parts[1];
                Cursor cursor = null;
                try {
                    cursor = context.getContentResolver().query(data, null, null, null, null);
                    if (cursor != null) {
                        logDebug("Cursor size:" + cursor.getCount());
                        if (cursor.moveToFirst()) {
                            if (data.toString().contains(Constants.VIDEO)) {
                                bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            } else if (data.toString().contains(Constants.IMAGE)) {
                                bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            }
                        }
                    }
                    return bitmap;
                } catch (Exception e) {
                    logError("Exception:" + e.getMessage() + " line: 266");
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
            }
            return bitmap;
        }
    });
}

From source file:com.colorchen.qbase.utils.FileUtil.java

@TargetApi(19)
public static String getPathFromUri(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }//  w ww .  j  a  va 2s  . co  m

        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return "";
}

From source file:com.av.remusic.service.MediaService.java

public boolean openFile(final String path) {
    if (D)//from  w w  w. j  a v  a2s  .  c om
        Log.d(TAG, "openFile: path = " + path);
    synchronized (this) {
        if (path == null) {
            return false;
        }

        if (mCursor == null) {
            Uri uri = Uri.parse(path);
            boolean shouldAddToPlaylist = true;
            long id = -1;
            try {
                id = Long.valueOf(uri.getLastPathSegment());
            } catch (NumberFormatException ex) {
                // Ignore
            }

            if (id != -1 && path.startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString())) {
                updateCursor(uri);

            } else if (id != -1 && path.startsWith(MediaStore.Files.getContentUri("external").toString())) {
                updateCursor(id);

            } else if (path.startsWith("content://downloads/")) {

                String mpUri = getValueForDownloadedFile(this, uri, "mediaprovider_uri");
                if (D)
                    Log.i(TAG, "Downloaded file's MP uri : " + mpUri);
                if (!TextUtils.isEmpty(mpUri)) {
                    if (openFile(mpUri)) {
                        notifyChange(META_CHANGED);
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    updateCursorForDownloadedFile(this, uri);
                    shouldAddToPlaylist = false;
                }

            } else {
                String where = MediaStore.Audio.Media.DATA + "=?";
                String[] selectionArgs = new String[] { path };
                updateCursor(where, selectionArgs);
            }
            try {
                if (mCursor != null && shouldAddToPlaylist) {
                    mPlaylist.clear();
                    mPlaylist.add(new MusicTrack(mCursor.getLong(IDCOLIDX), -1));
                    notifyChange(QUEUE_CHANGED);
                    mPlayPos = 0;
                    mHistory.clear();
                }
            } catch (final UnsupportedOperationException ex) {
                // Ignore
            }
        }

        mFileToPlay = path;
        mPlayer.setDataSource(mFileToPlay);
        if (mPlayer.isInitialized()) {
            mOpenFailedCounter = 0;
            return true;
        }

        String trackName = getTrackName();
        if (TextUtils.isEmpty(trackName)) {
            trackName = path;
        }
        sendErrorMessage(trackName);

        stop(true);
        return false;
    }
}

From source file:com.igniva.filemanager.fragments.ZipViewer.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    s = getArguments().getString("path");
    Uri uri = Uri.parse(s);
    f = new File(uri.getPath());
    mToolbarContainer = getActivity().findViewById(R.id.lin);
    mToolbarContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override//www . j  ava  2s . c om
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (stopAnims) {
                if ((!rarAdapter.stoppedAnimation)) {
                    stopAnim();
                }
                rarAdapter.stoppedAnimation = true;

            }
            stopAnims = false;
            return false;
        }
    });
    hidemode = Sp.getInt("hidemode", 0);
    listView.setVisibility(View.VISIBLE);
    mLayoutManager = new LinearLayoutManager(getActivity());
    listView.setLayoutManager(mLayoutManager);
    res = getResources();
    mainActivity.supportInvalidateOptionsMenu();
    if (mainActivity.theme1 == 1)
        rootView.setBackgroundColor(getResources().getColor(R.color.holo_dark_background));
    else
        listView.setBackgroundColor(getResources().getColor(android.R.color.background_light));

    gobackitem = Sp.getBoolean("goBack_checkbox", false);
    coloriseIcons = Sp.getBoolean("coloriseIcons", true);
    Calendar calendar = Calendar.getInstance();
    showSize = Sp.getBoolean("showFileSize", false);
    showLastModified = Sp.getBoolean("showLastModified", true);
    showDividers = Sp.getBoolean("showDividers", true);
    year = ("" + calendar.get(Calendar.YEAR)).substring(2, 4);
    skin = PreferenceUtils.getPrimaryColorString(Sp);
    accentColor = PreferenceUtils.getAccentString(Sp);
    iconskin = PreferenceUtils.getFolderColorString(Sp);

    theme = Integer.parseInt(Sp.getString("theme", "0"));
    theme1 = theme == 2 ? PreferenceUtils.hourOfDay() : theme;

    //mainActivity.findViewById(R.id.buttonbarframe).setBackgroundColor(Color.parseColor(skin));

    files = new ArrayList<>();
    if (savedInstanceState == null && f != null) {
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(null);
        } else {
            openmode = 0;
            SetupZip(null);
        }
    } else {
        f = new File(savedInstanceState.getString("file"));
        s = savedInstanceState.getString("uri");
        uri = Uri.parse(s);
        f = new File(uri.getPath());
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(savedInstanceState);
        } else {
            openmode = 0;
            SetupZip(savedInstanceState);
        }

    }
    String fileName = null;
    try {
        if (uri.getScheme().equals("file")) {
            fileName = uri.getLastPathSegment();
        } else {
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri,
                        new String[] { MediaStore.Images.ImageColumns.DISPLAY_NAME }, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor
                            .getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
                }
            } finally {

                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (fileName == null || fileName.trim().length() == 0)
        fileName = f.getName();
    try {
        mainActivity.setActionBarTitle(fileName);
    } catch (Exception e) {
        mainActivity.setActionBarTitle(getResources().getString(R.string.zip_viewer));
    }
    mainActivity.supportInvalidateOptionsMenu();
    mToolbarHeight = getToolbarHeight(getActivity());
    paddingTop = (mToolbarHeight) + dpToPx(72);
    mToolbarContainer.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    paddingTop = mToolbarContainer.getHeight();
                    mToolbarHeight = mainActivity.toolbar.getHeight();

                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }

            });

}

From source file:com.andrew.apollo.MusicPlaybackService.java

/**
 * Opens a file and prepares it for playback
 *
 * @param path The path of the file to open
 *//*  www.  j av  a  2  s  . com*/
public void openFile(final String path, final OpenFileResultCallback callback) {
    if (D)
        LOG.info("openFile: path = " + path);
    if (callback == null) {
        throw new IllegalArgumentException(
                "MusicPlaybackService.openFile requires a non null OpenFileResultCallback argument");
    }
    synchronized (this) {
        if (path == null) {
            callback.openFileResult(false);
            return;
        }

        // If mCursor is null, try to associate path with a database cursor
        if (mCursor == null) {
            Uri uri = Uri.parse(path);
            long id = -1;
            try {
                id = Long.valueOf(uri.getLastPathSegment());
            } catch (NumberFormatException ex) {
                // Ignore
            }

            if (id != -1 && path.startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString())) {
                updateCursor(uri);
            } else if (id != -1 && path.startsWith(MediaStore.Files.getContentUri("external").toString())) {
                updateCursor(id);
            } else {
                String where = MediaStore.Audio.Media.DATA + "=?";
                String[] selectionArgs = new String[] { path };
                updateCursor(where, selectionArgs);
            }
            try {
                if (mCursor != null) {
                    ensurePlayListCapacity(1);
                    mPlayListLen = 1;
                    mPlayList[0] = mCursor.getLong(IDCOLIDX);
                    mPlayPos = 0;
                }
            } catch (UnsupportedOperationException e) {
                LOG.error("Error while opening file for play", e);
                callback.openFileResult(false);
                return;
            } catch (StaleDataException | IllegalStateException e) {
                LOG.error("Error with database cursor while opening file for play", e);
                callback.openFileResult(false);
                return;
            }
        }
        mFileToPlay = path;
        if (mPlayer != null) { // machine state issues in general with original Apollo code
            mPlayer.setDataSource(mFileToPlay, () -> {
                if (mPlayer != null && mPlayer.isInitialized()) {
                    mOpenFailedCounter = 0;
                    callback.openFileResult(true);
                } else {
                    stop(true);
                    callback.openFileResult(false);
                }

            });
        } else {
            stop(true);
            callback.openFileResult(false);
        }
    }
}

From source file:org.openintents.shopping.ui.ShoppingActivity.java

private void setListUriFromIntent(Uri data, String type) {
    if (ShoppingContract.ITEM_TYPE.equals(type)) {
        mListUri = ShoppingUtils.getListForItem(this, data.getLastPathSegment());
    } else if (data != null) {
        mListUri = data;/*from   ww w.j  a  v  a 2 s .c  o  m*/
    }
}

From source file:im.vector.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs// ww w.j ava2  s  . c om
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    cursor.close();
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mConsoleMessageListFragment.uploadMediaContent(fMediaUrl, fMimeType,
                                                fFilename);
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}

From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java

/**
 * Upload a video message/*from   www .  jav  a 2s  . c  om*/
 *
 * @param thumbnailUrl      the thumbnail Url
 * @param thumbnailMimeType the thumbnail mime type
 * @param videoUrl          the video url
 * @param body              the message body
 * @param videoMimeType     the video mime type
 */
public void uploadVideoContent(final VideoMessage sourceVideoMessage, final MessageRow aVideoRow,
        final String thumbnailUrl, final String thumbnailMimeType, final String videoUrl, final String body,
        final String videoMimeType) {
    // create a tmp row
    VideoMessage tmpVideoMessage = sourceVideoMessage;
    Uri uri = null;
    Uri thumbUri = null;

    try {
        uri = Uri.parse(videoUrl);
        thumbUri = Uri.parse(thumbnailUrl);
    } catch (Exception e) {
        Log.e(LOG_TAG, "uploadVideoContent failed with " + e.getLocalizedMessage());
    }

    // the video message is not defined
    if (null == tmpVideoMessage) {
        tmpVideoMessage = new VideoMessage();
        tmpVideoMessage.url = videoUrl;
        tmpVideoMessage.body = body;

        try {
            Room.fillVideoInfo(getActivity(), tmpVideoMessage, uri, videoMimeType, thumbUri, thumbnailMimeType);
            if (null == tmpVideoMessage.body) {
                tmpVideoMessage.body = uri.getLastPathSegment();
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "uploadVideoContent : fillVideoInfo failed " + e.getLocalizedMessage());
        }
    }

    // remove any displayed MessageRow with this URL
    // to avoid duplicate
    final MessageRow videoRow = (null == aVideoRow) ? addMessageRow(tmpVideoMessage) : aVideoRow;
    videoRow.getEvent().mSentState = Event.SentState.SENDING;

    InputStream imageStream = null;
    String filename = "";
    String uploadId = "";
    String mimeType = "";

    MXEncryptedAttachments.EncryptionResult encryptionResult = null;
    try {
        // the thumbnail has been uploaded ?
        if (tmpVideoMessage.isThumbnailLocalContent()) {
            uploadId = thumbnailUrl;
            imageStream = new FileInputStream(new File(thumbUri.getPath()));
            mimeType = thumbnailMimeType;

            if (mRoom.isEncrypted() && mSession.isCryptoEnabled() && (null != imageStream)) {
                encryptionResult = MXEncryptedAttachments.encryptAttachment(imageStream, thumbnailMimeType);
                imageStream.close();

                if (null != encryptionResult) {
                    imageStream = encryptionResult.mEncryptedStream;
                    mimeType = "application/octet-stream";
                } else {
                    displayEncryptionAlert();
                    return;
                }
            }
        } else {
            uploadId = videoUrl;
            imageStream = new FileInputStream(new File(uri.getPath()));
            filename = tmpVideoMessage.body;
            mimeType = videoMimeType;

            if (mRoom.isEncrypted() && mSession.isCryptoEnabled() && (null != imageStream)) {
                encryptionResult = MXEncryptedAttachments.encryptAttachment(imageStream, thumbnailMimeType);
                imageStream.close();

                if (null != encryptionResult) {
                    imageStream = encryptionResult.mEncryptedStream;
                    mimeType = "application/octet-stream";
                } else {
                    displayEncryptionAlert();
                    return;
                }
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "uploadVideoContent : media parsing failed " + e.getLocalizedMessage());
    }

    final boolean isContentUpload = TextUtils.equals(uploadId, videoUrl);
    final VideoMessage fVideoMessage = tmpVideoMessage;
    final MXEncryptedAttachments.EncryptionResult fEncryptionResult = encryptionResult;

    getSession().getMediasCache().uploadContent(imageStream, filename, mimeType, uploadId,
            new MXMediaUploadListener() {
                @Override
                public void onUploadStart(String uploadId) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            onMessageSendingSucceeded(videoRow.getEvent());
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }

                @Override
                public void onUploadCancel(String uploadId) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            onMessageSendingFailed(videoRow.getEvent());
                        }
                    });
                }

                @Override
                public void onUploadError(final String uploadId, final int serverResponseCode,
                        final String serverErrorMessage) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            commonMediaUploadError(serverResponseCode, serverErrorMessage, videoRow);
                        }
                    });
                }

                @Override
                public void onUploadComplete(final String uploadId, final String contentUri) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            // the video content has been uploaded
                            if (isContentUpload) {
                                // replace the thumbnail and the media contents by the computed ones
                                getMXMediasCache().saveFileMediaForUrl(contentUri, videoUrl, videoMimeType);

                                if (null == fEncryptionResult) {
                                    fVideoMessage.url = contentUri;
                                } else {
                                    fEncryptionResult.mEncryptedFileInfo.url = contentUri;
                                    fVideoMessage.file = fEncryptionResult.mEncryptedFileInfo;
                                    fVideoMessage.url = null;
                                }

                                // update the event content with the new message info
                                videoRow.getEvent().updateContent(JsonUtils.toJson(fVideoMessage));

                                Log.d(LOG_TAG, "Uploaded to " + contentUri);

                                send(videoRow);
                            } else {
                                if (null == fEncryptionResult) {
                                    fVideoMessage.info.thumbnail_url = contentUri;
                                    getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl,
                                            mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(),
                                            thumbnailMimeType, true);
                                } else {
                                    fEncryptionResult.mEncryptedFileInfo.url = contentUri;
                                    fVideoMessage.info.thumbnail_file = fEncryptionResult.mEncryptedFileInfo;
                                    fVideoMessage.info.thumbnail_url = null;
                                    getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, -1, -1,
                                            thumbnailMimeType, true);
                                }

                                // update the event content with the new message info
                                videoRow.getEvent().updateContent(JsonUtils.toJson(fVideoMessage));

                                // upload the video
                                uploadVideoContent(fVideoMessage, videoRow, thumbnailUrl, thumbnailMimeType,
                                        videoUrl, fVideoMessage.body, videoMimeType);
                            }
                        }
                    });
                }
            });
}

From source file:com.cyanogenmod.eleven.MusicPlaybackService.java

/**
 * Opens a file and prepares it for playback
 *
 * @param path The path of the file to open
 *///from   w w  w . ja va  2 s. c  o  m
public boolean openFile(final String path) {
    if (D)
        Log.d(TAG, "openFile: path = " + path);
    synchronized (this) {
        if (path == null) {
            return false;
        }

        // If mCursor is null, try to associate path with a database cursor
        if (mCursor == null) {
            Uri uri = Uri.parse(path);
            boolean shouldAddToPlaylist = true; // should try adding audio info to playlist
            long id = -1;
            try {
                id = Long.valueOf(uri.getLastPathSegment());
            } catch (NumberFormatException ex) {
                // Ignore
            }

            if (id != -1 && path.startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString())) {
                updateCursor(uri);

            } else if (id != -1 && path.startsWith(MediaStore.Files.getContentUri("external").toString())) {
                updateCursor(id);

                // handle downloaded media files
            } else if (path.startsWith("content://downloads/")) {

                // extract MediaProvider(MP) uri , if available
                // Downloads.Impl.COLUMN_MEDIAPROVIDER_URI
                String mpUri = getValueForDownloadedFile(this, uri, "mediaprovider_uri");
                if (D)
                    Log.i(TAG, "Downloaded file's MP uri : " + mpUri);
                if (!TextUtils.isEmpty(mpUri)) {
                    // if mpUri is valid, play that URI instead
                    if (openFile(mpUri)) {
                        // notify impending change in track
                        notifyChange(META_CHANGED);
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    // create phantom cursor with download info, if a MP uri wasn't found
                    updateCursorForDownloadedFile(this, uri);
                    shouldAddToPlaylist = false; // song info isn't available in MediaStore
                }

            } else {
                // assuming a "file://" uri by this point ...
                String where = MediaStore.Audio.Media.DATA + "=?";
                String[] selectionArgs = new String[] { path };
                updateCursor(where, selectionArgs);
            }
            try {
                if (mCursor != null && shouldAddToPlaylist) {
                    mPlaylist.clear();
                    mPlaylist.add(new MusicPlaybackTrack(mCursor.getLong(IDCOLIDX), -1, IdType.NA, -1));
                    // propagate the change in playlist state
                    notifyChange(QUEUE_CHANGED);
                    mPlayPos = 0;
                    mHistory.clear();
                }
            } catch (final UnsupportedOperationException ex) {
                // Ignore
            }
        }

        mFileToPlay = path;
        mPlayer.setDataSource(mFileToPlay);
        if (mPlayer.isInitialized()) {
            mOpenFailedCounter = 0;
            return true;
        }

        String trackName = getTrackName();
        if (TextUtils.isEmpty(trackName)) {
            trackName = path;
        }
        sendErrorMessage(trackName);

        stop(true);
        return false;
    }
}