Example usage for android.net Uri getScheme

List of usage examples for android.net Uri getScheme

Introduction

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

Prototype

@Nullable
public abstract String getScheme();

Source Link

Document

Gets the scheme of this URI.

Usage

From source file:com.popcorntime.apps.remote.utils.Utils.java

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Log.i("uri", contentUri.toString());
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        Cursor cursor = null;//from  w ww  . j  ava  2  s  .  com
        try {

            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } else {
        Uri uri = contentUri;
        // DocumentProvider
        if (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];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

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

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

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

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

                return getDataColumn(context, contentUri2, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }
}

From source file:com.erhuoapp.erhuo.activity.ChatActivity.java

/**
 * ??/*  w  w  w.j av a2 s  .c  o m*/
 * 
 * @param uri
 */
private void sendFile(Uri uri) {
    String filePath = null;
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        filePath = uri.getPath();
    }
    File file = new File(filePath);
    if (file == null || !file.exists()) {
        String st7 = getResources().getString(R.string.File_does_not_exist);
        Toast.makeText(getApplicationContext(), st7, 0).show();
        return;
    }
    if (file.length() > 10 * 1024 * 1024) {
        String st6 = getResources().getString(R.string.The_file_is_not_greater_than_10_m);
        Toast.makeText(getApplicationContext(), st6, 0).show();
        return;
    }

    // ?
    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
    // ?chattype,??
    if (chatType == CHATTYPE_GROUP)
        message.setChatType(ChatType.GroupChat);

    message.setReceipt(toChatUsername);
    // add message body
    NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
    message.addBody(body);

    EntityUserInfo userInfo = AppUtil.getInstance().getBasicUserInfo();
    message.setAttribute("from", userInfo.getNickName());
    message.setAttribute("fromheader", userInfo.getHeader());
    message.setAttribute("fromid", userInfo.getId());

    String id = getIntent().getStringExtra("userId");
    HeadAndName mHeadAndName = new HeadAndName(this);
    UserHeadAndName mUserHeadAndName = mHeadAndName.selectOne(id);
    message.setAttribute("to", mUserHeadAndName.getNick());
    message.setAttribute("toheader", mUserHeadAndName.getHead());

    conversation.addMessage(message);
    listView.setAdapter(adapter);
    adapter.refresh();
    listView.setSelection(listView.getCount() - 1);
    setResult(RESULT_OK);
}

From source file:edu.mit.mobile.android.locast.data.Sync.java

/**
 * Given a live cursor pointing to a data item and/or a set of contentValues loaded from the network,
 * attempt to sync.//from   w w w  .jav a 2s  .  c om
 * Either c or cvNet can be null, but not both.
 * @param c A cursor pointing to the data item. Null is OK here.
 * @param jsonObject JSON object for the item as loaded from the network. null is OK here.
 * @param sync An empty JsonSyncableItem object.
 * @param publicPath TODO
 *
 * @return True if the item has been modified on either end.
 * @throws IOException
 */
private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync,
        SyncProgressNotifier syncProgress, String publicPath) throws SyncException, IOException {
    boolean modified = false;
    boolean needToCloseCursor = false;
    boolean toSyncIsIndex = false;
    final SyncMap syncMap = sync.getSyncMap();

    Uri locUri = null;
    final Uri origToSync = toSync;
    ContentValues cvNet = null;

    final Context context = getApplicationContext();
    final ContentResolver cr = context.getContentResolver();
    if (jsonObject != null) {
        if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
            // we successfully loaded it from the 'net, but toSync is really for local URIs. Erase it.

            toSync = sync.getContentUri();
            if (toSync == null) {
                if (DEBUG) {
                    Log.w(TAG, "cannot get local URI for " + origToSync + ". Skipping...");
                }
                return false;
            }
        }
        try {
            cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap);
        } catch (final Exception e) {
            final SyncException se = new SyncException("Problem loading JSON object.");
            se.initCause(e);
            throw se;
        }
    }

    final String contentType = cr.getType(toSync);

    if (c != null) {
        if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
            locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID)))
                    .buildUpon().query(null).build();
            toSyncIsIndex = true;
        } else {
            locUri = toSync;
        }

        // skip any items already sync'd
        if (mLastUpdated.isUpdatedRecently(locUri)) {
            return false;
        }

        final int draftCol = c.getColumnIndex(TaggableItem._DRAFT);
        if (draftCol != -1 && c.getInt(draftCol) != 0) {
            if (DEBUG) {
                Log.d(TAG, locUri + " is marked a draft. Not syncing.");
            }
            return false;
        }

        syncMap.onPreSyncItem(cr, locUri, c);
    } else if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
        // strip any query strings
        toSync = toSync.buildUpon().query(null).build();
    }
    //      if (c != null){
    //         MediaProvider.dumpCursorToLog(c, sync.getFullProjection());
    //      }
    // when the PUBLIC_URI is null, that means it's only local
    final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1;
    if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")) {
        // new content on the local side only. Gotta publish.

        try {
            jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap);
            if (publicPath == null) {
                publicPath = MediaProvider.getPostPath(this, locUri);
            }
            if (DEBUG) {
                Log.d(TAG, "Posting " + locUri + " to " + publicPath);
            }

            // The response from a post to create a new item should be the newly created item,
            // which contains the public ID that we need.
            jsonObject = nc.postJson(publicPath, jsonObject);

            final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
            if (cr.update(locUri, cvUpdate, null, null) == 1) {
                // at this point, server and client should be in sync.
                mLastUpdated.markUpdated(locUri);
                if (DEBUG) {
                    Log.i(TAG, "Hooray! " + locUri + " has been posted succesfully.");
                }

            } else {
                Log.e(TAG, "update of " + locUri + " failed");
            }
            modified = true;

        } catch (final Exception e) {
            final SyncException se = new SyncException(getString(R.string.error_sync_no_post));
            se.initCause(e);
            throw se;
        }

        // only on the remote side, so pull it in.
    } else if (c == null && cvNet != null) {
        if (DEBUG) {
            Log.i(TAG, "Only on the remote side, using network-provided values.");
        }
        final String[] params = { cvNet.getAsString(JsonSyncableItem._PUBLIC_URI) };
        c = cr.query(toSync, sync.getFullProjection(), JsonSyncableItem._PUBLIC_URI + "=?", params, null);
        needToCloseCursor = true;

        if (!c.moveToFirst()) {
            locUri = cr.insert(toSync, cvNet);
            modified = true;
        } else {
            locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID)))
                    .buildUpon().query(null).build();
            syncMap.onPreSyncItem(cr, locUri, c);
        }
    }

    // we've now found data on both sides, so sync them.
    if (!modified && c != null) {

        publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI));

        try {

            if (cvNet == null) {
                try {
                    if (publicPath == null && toSyncIsIndex && !MediaProvider.canSync(locUri)) {

                        // At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems).
                        // If we can't sync individual items, it's possible that the index is paged or the item has been deleted.
                        if (DEBUG) {
                            Log.w(TAG, "Asked to sync " + locUri
                                    + " but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date.");
                        }
                        return false;

                    } else {
                        if (mLastUpdated.isUpdatedRecently(nc.getFullUri(publicPath))) {
                            if (DEBUG) {
                                Log.d(TAG, "already sync'd! " + publicPath);
                            }
                            return false;
                        }
                        if (jsonObject == null) {
                            jsonObject = nc.getObject(publicPath);
                        }
                        cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);

                    }
                } catch (final HttpResponseException hre) {
                    if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                        final SyncItemDeletedException side = new SyncItemDeletedException(locUri);
                        side.initCause(hre);
                        throw side;
                    }
                }
            }
            if (cvNet == null) {
                Log.e(TAG, "got null values from fromJSON() on item " + locUri + ": "
                        + (jsonObject != null ? jsonObject.toString() : "<< no json object >>"));
                return false;
            }
            final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE));
            final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE)));

            if (netLastModified.equals(locLastModified)) {
                // same! yay! We don't need to do anything.
                if (DEBUG) {
                    Log.d("LocastSync", locUri + " doesn't need to sync.");
                }
            } else if (netLastModified.after(locLastModified)) {
                // remote is more up to date, update!
                cr.update(locUri, cvNet, null, null);
                if (DEBUG) {
                    Log.d("LocastSync", cvNet + " is newer than " + locUri);
                }
                modified = true;

            } else if (netLastModified.before(locLastModified)) {
                // local is more up to date, propagate!
                jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap));

                if (DEBUG) {
                    Log.d("LocastSync", cvNet + " is older than " + locUri);
                }
                modified = true;
            }
            mLastUpdated.markUpdated(nc.getFullUri(publicPath));
        } catch (final JSONException e) {
            final SyncException se = new SyncException(
                    "Item sync error for path " + publicPath + ": invalid JSON.");
            se.initCause(e);
            throw se;
        } catch (final NetworkProtocolException e) {
            final SyncException se = new SyncException(
                    "Item sync error for path " + publicPath + ": " + e.getHttpResponseMessage());
            se.initCause(e);
            throw se;
        } finally {
            if (needToCloseCursor) {
                c.close();
                needToCloseCursor = false;
            }
        }
    }

    if (needToCloseCursor) {
        c.close();
    }

    if (locUri == null) {
        throw new RuntimeException("Never got a local URI for a sync'd item.");
    }

    // two calls are made in two different contexts. Which context you use depends on the application.
    syncMap.onPostSyncItem(context, locUri, jsonObject, modified);
    sync.onPostSyncItem(context, locUri, jsonObject, modified);

    mLastUpdated.markUpdated(locUri);

    // needed for things that may have requested a sync with a different URI than what was eventually produced.
    if (origToSync != locUri) {
        mLastUpdated.markUpdated(origToSync);
        cr.notifyChange(origToSync, null);
    }

    return modified;
}

From source file:com.android.contacts.common.ContactPhotoManager.java

protected boolean isDefaultImageUri(Uri uri) {
    return DEFAULT_IMAGE_URI_SCHEME.equals(uri.getScheme());
}

From source file:hku.fyp14017.blencode.ui.controller.SoundController.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders./*w  w  w. j av  a  2 s .  co  m*/
 * <p/>
 * <p/>
 * solution according to:
 * http://stackoverflow.com/questions/19834842/android-gallery-on-kitkat-returns-different-uri
 * -for-intent-action-get-content
 * 
 * @author paulburke
 */
@TargetApi(19)
private static String getPathForVersionAboveEqualsVersion19(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];
            }

            // 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:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(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 w w .  j  a v a  2 s  .c om

            // 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 getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.android.mail.browse.ConversationCursor.java

/**
 * Regenerate the original Uri from a forwarding (ConversationProvider) Uri
 * NOTE: See note above for uriToCachingUri
 * @param uri the forwarding Uri/*w  ww  .  j a va2s.c  om*/
 * @return the original Uri
 */
private static Uri uriFromCachingUri(Uri uri) {
    String authority = uri.getAuthority();
    // Don't modify uri's that aren't ours
    if (!authority.equals(ConversationProvider.AUTHORITY)) {
        return uri;
    }
    List<String> path = uri.getPathSegments();
    Uri.Builder builder = new Uri.Builder().scheme(uri.getScheme()).authority(path.get(0));
    for (int i = 1; i < path.size(); i++) {
        builder.appendPath(path.get(i));
    }
    return builder.build();
}

From source file:com.google.code.twisty.Twisty.java

void startTerp(Uri gameURI) throws IOException, MalformedURLException {

    /* Set up output file in same directory as saved-games. */
    String dir = getSavedGamesDir(true);
    if (dir == null) {
        showDialog(DIALOG_CANT_SAVE);//from www  .j a va 2 s  . c  o m
        return;
    }

    String uriString = gameURI.toString();
    String gameFilename = uriString.substring(uriString.lastIndexOf("/") + 1);
    File outputFile = new File(dir, gameFilename);

    // Copy the input file into our story directory, unless the input and output file
    // would be the same. This check currently doesn't support uri's that don't contain
    // the file path. In that case the file will be corrupted.
    if (!((gameURI.getScheme().equals("content") || gameURI.getScheme().equals("file"))
            && gameURI.toString().contains(outputFile.getCanonicalPath()))) {
        FileOutputStream gameOutputStream = null;
        try {
            outputFile.createNewFile();
            gameOutputStream = new FileOutputStream(outputFile);
        } catch (IOException e) {
            Log.i(TAG, "Failed to create file called " + gameFilename);
            return;
        }

        /* Set up input from URI */
        InputStream gameInputStream = null;

        if (gameURI.getScheme().equals("content")) {
            try {
                gameInputStream = getContentResolver().openInputStream(gameURI);
            } catch (FileNotFoundException e) {
                Log.i(TAG, "Failed to open file: " + uriString);
                gameOutputStream.close();
                return;
            }
        } else {
            try {
                URL gameURL = new URL(uriString);
                URLConnection connection = gameURL.openConnection();
                connection.connect();
                gameInputStream = connection.getInputStream();
            } catch (MalformedURLException e) {
                Log.i(TAG, "Received malformed URI: " + uriString);
                gameOutputStream.close();
                return;
            } catch (IOException e) {
                Log.i(TAG, "Failed to open connection to URI: " + uriString);
                gameOutputStream.close();
                return;
            }
        }

        try {
            Log.i(TAG, "About to spew raw data to disk...");
            suckstream(gameInputStream, gameOutputStream);
        } catch (IOException e) {
            Log.i(TAG, "Failed to copy URL contents to local file: " + uriString);
            return;
        }
        Log.i(TAG, "Completed dump of raw data to disk.");
    } else
        Log.i(TAG, "Input and output file are the same: " + outputFile.getCanonicalPath());

    Log.i(TAG, "Starting gamefile located at " + outputFile.getCanonicalPath());
    startTerp(outputFile.getCanonicalPath());
}

From source file:com.teeptrak.controller.MainActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_SELECT_DEVICE: {
        //When the DeviceListActivity return, with the selected device address
        if (resultCode == Activity.RESULT_OK && data != null) {
            String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
            mBtDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);

            Log.d(TAG, "... onActivityResultdevice.address==" + mBtDevice + "mserviceValue" + mUartService);

            mBtDeviceName.setText(mBtDevice.getName() + " - Connecting");

            if (mBtDevice.getName().equals("DfuTarg")) {
                if (mFwFilePath != null) {
                    final DfuServiceInitiator DFU = new DfuServiceInitiator(mBtDevice.getAddress())
                            .setDeviceName(mBtDevice.getName()).setKeepBond(false).setZip(null, mFwFilePath);
                    DFU.start(this, DfuService.class);
                } else {
                    printMessage("Selected Device is in DFU mode.", false);
                    printMessage("You must Set FirmWare file first!", false);
                    Toast.makeText(this, "You must Set FirmWare file first!", Toast.LENGTH_SHORT).show();
                }//  ww  w  .  ja v  a  2  s  .  c  om
            } else {
                mUartService.connect(deviceAddress);
            }
        }
        break;
    }

    case REQUEST_ENABLE_BT: {
        // When the request to enable Bluetooth returns
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();
        } else {
            // User did not enable Bluetooth or an error occurred
            Log.d(TAG, "BT not enabled");
            Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
            finish();
        }
        break;
    }

    case REQUEST_SELECT_FILE: {
        // Clear previous data
        mFwFilePath = null;
        mCfgFilePath = null;
        mTstFilePath = null;
        //mFileUri = null;

        // Read new one
        final Uri uri = data.getData();
        /*
         * The URI returned from application may be in 'file' or 'content' schema.
         * 'File' schema allows us to create a File object and read details from it
         * directly. Data from 'Content' schema must be read by Content Provider.
         * To do that we are using a Loader.
         */
        if (uri.getScheme().equals("file")) {
            // the direct path to the file has been returned
            final String path = uri.getPath();
            final File file = new File(path);

            switch (mFileType) {
            case FILE_TYPE_ZIP:
                mFwFilePath = path;
                break;
            case FILE_TYPE_CFG:
                mCfgFilePath = path;
                break;
            case FILE_TYPE_TST:
                mTstFilePath = path;
                break;
            case FILE_TYPE_NONE:
            default:
                break;
            }

            updateFileInfo(file.getName(), file.length(), path, mFileType);
        } else if (uri.getScheme().equals("content")) {
            // an Uri has been returned
            //mFileUri = uri;
            // If application returned Uri for streaming, let's use it. Does it works?
            // FIXME both Uris works with Google Drive app. Why both? What's the difference?
            // How about other apps like DropBox?
            final Bundle extras = data.getExtras();
            //if(extras != null && extras.containsKey(Intent.EXTRA_STREAM))
            //    mFileUri = extras.getParcelable(Intent.EXTRA_STREAM);

            // File name and size must be obtained from Content Provider
            final Bundle bundle = new Bundle();
            bundle.putParcelable(EXTRA_URI, uri);
            getLoaderManager().restartLoader(REQUEST_SELECT_FILE, bundle, this);
        }
        break;
    }

    default:
        Log.e(TAG, "wrong request code");
        break;
    }
}

From source file:cn.kangeqiu.kq.activity.ChatActivity.java

/**
 * ??//from  www .j  a v a2 s .  c  o  m
 * 
 * @param uri
 */
private void sendFile(Uri uri) {
    String filePath = null;
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        filePath = uri.getPath();
    }
    File file = new File(filePath);
    if (file == null || !file.exists()) {
        String st7 = getResources().getString(R.string.File_does_not_exist);
        Toast.makeText(getApplicationContext(), st7, 0).show();
        return;
    }
    if (file.length() > 10 * 1024 * 1024) {
        String st6 = getResources().getString(R.string.The_file_is_not_greater_than_10_m);
        Toast.makeText(getApplicationContext(), st6, 0).show();
        return;
    }

    // ?
    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
    // ?chattype,??
    if (chatType == CHATTYPE_GROUP)
        message.setChatType(ChatType.GroupChat);

    message.setReceipt(toChatUsername);
    // add message body
    NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
    message.addBody(body);
    conversation.addMessage(message);
    listView.setAdapter(adapter);
    adapter.refresh();
    listView.setSelection(listView.getCount() - 1);
    setResult(RESULT_OK);
}