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.devalladolid.musictoday.MusicService.java

public boolean openFile(final String path) {
    if (D)/*from  w w  w.  j  av  a  2  s  .com*/
        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 MusicPlaybackTrack(mCursor.getLong(IDCOLIDX), -1, TimberUtils.IdType.NA, -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:net.voxcorp.voxmobile.db.DBProvider.java

@Override
public int delete(Uri uri, String where, String[] whereArgs) {

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    String finalWhere;//  w  w w.  j a va  2 s .co  m
    int count = 0;
    int matched = URI_MATCHER.match(uri);
    Uri regUri = uri;

    List<String> possibles = getPossibleFieldsForType(matched);
    checkSelection(possibles, where);

    ArrayList<Long> oldRegistrationsAccounts = null;

    switch (matched) {
    case ACCOUNTS:
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, where, whereArgs);
        break;
    case ACCOUNTS_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipProfile.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case CALLLOGS:
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, where, whereArgs);
        break;
    case CALLLOGS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(CallLog.Calls._ID + " = " + ContentUris.parseId(uri),
                where);
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case FILTERS:
        count = db.delete(SipManager.FILTERS_TABLE_NAME, where, whereArgs);
        break;
    case FILTERS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(Filter._ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipManager.FILTERS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case MESSAGES:
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, where, whereArgs);
        break;
    case MESSAGES_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipMessage.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, finalWhere, whereArgs);
        break;
    case THREADS_ID:
        String from = uri.getLastPathSegment();
        if (!TextUtils.isEmpty(from)) {
            count = db.delete(SipMessage.MESSAGES_TABLE_NAME, MESSAGES_THREAD_SELECTION,
                    new String[] { from, from });
        } else {
            count = 0;
        }
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        oldRegistrationsAccounts = new ArrayList<Long>();
        synchronized (profilesStatus) {
            for (Long accId : profilesStatus.keySet()) {
                oldRegistrationsAccounts.add(accId);
            }
            profilesStatus.clear();
        }
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            profilesStatus.remove(id);
        }
        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    getContext().getContentResolver().notifyChange(regUri, null);

    if (matched == ACCOUNTS_ID || matched == ACCOUNTS_STATUS_ID) {
        long rowId = ContentUris.parseId(uri);
        if (rowId >= 0) {
            if (matched == ACCOUNTS_ID) {
                broadcastAccountChange(rowId);
            } else if (matched == ACCOUNTS_STATUS_ID) {
                broadcastRegistrationChange(rowId);
            }
        }
    }
    if (matched == FILTERS || matched == FILTERS_ID) {
        Filter.resetCache();
    }
    if (matched == ACCOUNTS_STATUS && oldRegistrationsAccounts != null) {
        for (Long accId : oldRegistrationsAccounts) {
            if (accId != null) {
                broadcastRegistrationChange(accId);
            }
        }
    }

    return count;
}

From source file:com.csipsimple.db.DBProvider.java

@Override
public int delete(Uri uri, String where, String[] whereArgs) {

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    String finalWhere;//from   w w  w  .j  a v a2s.c o  m
    int count = 0;
    int matched = URI_MATCHER.match(uri);
    Uri regUri = uri;

    List<String> possibles = getPossibleFieldsForType(matched);
    checkSelection(possibles, where);

    ArrayList<Long> oldRegistrationsAccounts = null;

    switch (matched) {
    case ACCOUNTS:
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, where, whereArgs);
        break;
    case ACCOUNTS_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipProfile.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case CALLLOGS:
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, where, whereArgs);
        break;
    case CALLLOGS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(CallLog.Calls._ID + " = " + ContentUris.parseId(uri),
                where);
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case FILTERS:
        count = db.delete(SipManager.FILTERS_TABLE_NAME, where, whereArgs);
        break;
    case FILTERS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(Filter._ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipManager.FILTERS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case MESSAGES:
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, where, whereArgs);
        break;
    case MESSAGES_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipMessage.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, finalWhere, whereArgs);
        break;
    case THREADS_ID:
        String from = uri.getLastPathSegment();
        if (!TextUtils.isEmpty(from)) {
            count = db.delete(SipMessage.MESSAGES_TABLE_NAME, MESSAGES_THREAD_SELECTION,
                    new String[] { from, from });
        } else {
            count = 0;
        }
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        oldRegistrationsAccounts = new ArrayList<Long>();
        synchronized (profilesStatus) {
            for (Long accId : profilesStatus.keySet()) {
                oldRegistrationsAccounts.add(accId);
            }
            profilesStatus.clear();
        }
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            profilesStatus.remove(id);
        }
        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    getContext().getContentResolver().notifyChange(regUri, null);

    if (matched == ACCOUNTS_ID || matched == ACCOUNTS_STATUS_ID) {
        long rowId = ContentUris.parseId(uri);
        if (rowId >= 0) {
            if (matched == ACCOUNTS_ID) {
                broadcastAccountDelete(rowId);
            } else if (matched == ACCOUNTS_STATUS_ID) {
                broadcastRegistrationChange(rowId);
            }
        }
    }
    if (matched == FILTERS || matched == FILTERS_ID) {
        Filter.resetCache();
    }
    if (matched == ACCOUNTS_STATUS && oldRegistrationsAccounts != null) {
        for (Long accId : oldRegistrationsAccounts) {
            if (accId != null) {
                broadcastRegistrationChange(accId);
            }
        }
    }

    return count;
}

From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java

@SuppressLint("NewApi")
private String getPath(Context context, 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];
            }/*from ww w  .  j a  va2  s  . c o  m*/
            // TODO handle non-primary volumes
        }
        // 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 null;
}

From source file:de.ub0r.android.websms.WebSMS.java

/**
 * Parse data pushed by {@link Intent}.//from   ww  w. j  a v a  2  s. c  o m
 *
 * @param intent {@link Intent}
 */
private void parseIntent(final Intent intent) {
    final String action = intent.getAction();
    Log.d(TAG, "launched with action: " + action);
    if (action == null) {
        return;
    }
    final Uri uri = intent.getData();
    Log.i(TAG, "launched with uri: " + uri);
    if (uri != null && uri.toString().length() > 0) {
        // launched by clicking a sms: link, target number is in URI.
        final String scheme = uri.getScheme();
        if (scheme != null) {
            if (scheme.equals("sms") || scheme.equals("smsto")) {
                final String s = uri.getSchemeSpecificPart();
                this.parseSchemeSpecificPart(s);
            } else if (scheme.equals("content")) {
                this.parseThreadId(uri.getLastPathSegment());
            }
        }
    }
    // check for extras
    String s = intent.getStringExtra("address");
    if (!TextUtils.isEmpty(s)) {
        Log.d(TAG, "got address: " + s);
        this.lastTo = s;
    }
    s = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (s == null) {
        Log.d(TAG, "got sms_body: " + s);
        s = intent.getStringExtra("sms_body");
    }
    if (s == null) {
        final Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
        if (stream != null) {
            Log.d(TAG, "got stream: " + stream);
            try {
                InputStream is = this.getContentResolver().openInputStream(stream);
                final BufferedReader r = new BufferedReader(new InputStreamReader(is));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = r.readLine()) != null) {
                    sb.append(line + "\n");
                }
                s = sb.toString().trim();
            } catch (IOException e) {
                Log.e(TAG, "IO ERROR", e);
            }

        }
    }
    if (s != null) {
        Log.d(TAG, "set text: " + s);
        ((EditText) this.findViewById(R.id.text)).setText(s);
        this.lastMsg = s;
    }
    s = intent.getStringExtra(EXTRA_ERRORMESSAGE);
    if (s != null) {
        Log.e(TAG, "show error: " + s);
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
    }
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
    if (p.getBoolean(PREFS_AUTOSEND, true)) {
        s = intent.getStringExtra(WebSMS.EXTRA_AUTOSEND);
        Log.d(TAG, "try autosend..");
        Log.d(TAG, "s: " + s);
        Log.d(TAG, "lastMsg: " + this.lastMsg);
        Log.d(TAG, "lastTo: " + this.lastTo);

        if (s != null && !TextUtils.isEmpty(this.lastMsg) && !TextUtils.isEmpty(this.lastTo)) {
            // all data is here
            Log.d(TAG, "do autosend");
            if (p.getBoolean(PREFS_USE_CURRENT_CON, true)) {
                // push it to current active connector
                Log.d(TAG, "use current connector");
                if (prefsConnectorSpec != null && prefsSubConnectorSpec != null) {
                    Log.d(TAG, "autosend: call send()");
                    if (this.send(prefsConnectorSpec, prefsSubConnectorSpec) && !this.isFinishing()) {
                        Log.d(TAG, "sent successfully");
                        this.finish();
                    }
                }
            } else {
                // show connector chooser
                Log.d(TAG, "show connector chooser");
                final AlertDialog.Builder b = new AlertDialog.Builder(this);
                b.setTitle(R.string.change_connector_);
                final ConnectorLabel[] items = this.getConnectorMenuItems(true /*isIncludePseudoConnectors*/);
                Log.d(TAG, "show #items: " + items.length);
                if (items.length > 0) {
                    b.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(final DialogInterface dialog, final int which) {
                            final ConnectorLabel sel = items[which];
                            // save old selected connector
                            final ConnectorSpec pr0 = prefsConnectorSpec;
                            final SubConnectorSpec pr1 = prefsSubConnectorSpec;
                            // switch to selected
                            WebSMS.this.saveSelectedConnector(sel.getConnector(), sel.getSubConnector());
                            // send message
                            boolean sent = false;
                            Log.d(TAG, "autosend: call send()");
                            if (prefsConnectorSpec != null && prefsSubConnectorSpec != null) {
                                sent = WebSMS.this.send(prefsConnectorSpec, prefsSubConnectorSpec);
                            }
                            // restore old connector
                            WebSMS.this.saveSelectedConnector(pr0, pr1);
                            // quit
                            if (sent && !WebSMS.this.isFinishing()) {
                                Log.d(TAG, "sent successfully");
                                WebSMS.this.finish();
                            }
                        }
                    });
                    b.setNegativeButton(android.R.string.cancel, null);
                    b.show();
                }
            }
        }
    }
}

From source file:org.awesomeapp.messenger.ui.ConversationView.java

private void sendStickerCode(Uri assetUri) {
    StringBuffer stickerCode = new StringBuffer();
    stickerCode.append(":");

    stickerCode.append(assetUri.getPathSegments().get(assetUri.getPathSegments().size() - 2));
    stickerCode.append("-");
    stickerCode.append(assetUri.getLastPathSegment().split("\\.")[0]);

    stickerCode.append(":");

    sendMessageAsync(stickerCode.toString());
}

From source file:com.xxxifan.devbox.library.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 www. j  a  va2s .co 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)) {
                Log.e(TAG, "Not a media uri");
                if (isGoogleDriveDocument(data)) {
                    Log.e(TAG, "Google Drive Uri");
                    DocumentFile file = DocumentFile.fromSingleUri(context, data);
                    if (file.getType().startsWith(Constants.IMAGE_TYPE)
                            || file.getType().startsWith(Constants.VIDEO_TYPE)) {
                        Log.e(TAG, "Google Drive Uri");
                        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) {
                            e.printStackTrace();
                        }
                    }
                } else if (data.getScheme().equals(Constants.FILE)) {
                    Log.e(TAG, "Dropbox or other content provider");
                    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) {
                        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) {
                        e.printStackTrace();
                    }
                }
            } else {
                Log.e(TAG, "Uri for thumbnail: " + data.toString());
                Log.e(TAG, "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) {
                        Log.e(TAG, "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)) {
                                Log.e(TAG, "Image Uri");
                                bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),
                                        Long.parseLong(fileId), kind, options);
                            }
                            Log.e(TAG, bitmap == null ? "null" : "not null");
                        }
                    }
                    return bitmap;
                } catch (Exception e) {
                    Log.e(TAG, "Exception while getting thumbnail:" + e.getMessage());
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
            }
            return bitmap;
        }
    });
}

From source file:com.bluros.music.MusicService.java

public boolean openFile(final String path) {
    if (D)/*from w w w  .  j a  va  2  s  . c  o  m*/
        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 MusicPlaybackTrack(mCursor.getLong(IDCOLIDX), -1, MusicUtils.IdType.NA, -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.koma.music.service.MusicService.java

/**
 * Opens a file and prepares it for playback
 *
 * @param path The path of the file to open
 *//*from  w w  w .j a va 2s .  c  om*/
public boolean openFile(final String path) {
    LogUtils.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");
                LogUtils.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(MusicServiceConstants.IDCOLIDX), -1, -1));
                    // propagate the change in playlist state
                    notifyChange(MusicServiceConstants.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;
    }
}