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.tasomaniac.openwith.resolver.ResolverActivity.java

protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {

    final ChooserHistory history = getHistory();

    if ((mAlwaysUseOption || mAdapter.hasFilteredItem()) && mAdapter.mOrigResolveList != null) {
        // Build a reasonable intent filter, based on what matched.
        IntentFilter filter = new IntentFilter();

        if (intent.getAction() != null) {
            filter.addAction(intent.getAction());
        }/*from   ww  w.ja v  a 2s. c o m*/
        Set<String> categories = intent.getCategories();
        if (categories != null) {
            for (String cat : categories) {
                filter.addCategory(cat);
            }
        }
        filter.addCategory(Intent.CATEGORY_DEFAULT);

        int cat = ri.match & IntentFilter.MATCH_CATEGORY_MASK;
        Uri data = intent.getData();
        if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
            String mimeType = intent.resolveType(this);
            if (mimeType != null) {
                try {
                    filter.addDataType(mimeType);
                } catch (IntentFilter.MalformedMimeTypeException e) {
                    Log.w("ResolverActivity", e);
                    filter = null;
                }
            }
        }
        if (filter != null && data != null && data.getScheme() != null) {
            // We need the data specification if there was no type,
            // OR if the scheme is not one of our magical "file:"
            // or "content:" schemes (see IntentFilter for the reason).
            if (cat != IntentFilter.MATCH_CATEGORY_TYPE
                    || (!"file".equals(data.getScheme()) && !"content".equals(data.getScheme()))) {
                filter.addDataScheme(data.getScheme());

                // Look through the resolved filter to determine which part
                // of it matched the original Intent.
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    Iterator<PatternMatcher> pIt = ri.filter.schemeSpecificPartsIterator();

                    if (pIt != null) {
                        String ssp = data.getSchemeSpecificPart();
                        while (ssp != null && pIt.hasNext()) {
                            PatternMatcher p = pIt.next();
                            if (p.match(ssp)) {
                                filter.addDataSchemeSpecificPart(p.getPath(), p.getType());
                                break;
                            }
                        }
                    }
                }
                Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
                if (aIt != null) {
                    while (aIt.hasNext()) {
                        IntentFilter.AuthorityEntry a = aIt.next();
                        if (a.match(data) >= 0) {
                            int port = a.getPort();
                            filter.addDataAuthority(a.getHost(), port >= 0 ? Integer.toString(port) : null);
                            break;
                        }
                    }
                }
                Iterator<PatternMatcher> pIt = ri.filter.pathsIterator();
                if (pIt != null) {
                    String path = data.getPath();
                    while (path != null && pIt.hasNext()) {
                        PatternMatcher p = pIt.next();
                        if (p.match(path)) {
                            filter.addDataPath(p.getPath(), p.getType());
                            break;
                        }
                    }
                }
            }
        }

        if (filter != null) {
            ContentValues values = new ContentValues(3);
            values.put(HOST, mRequestedUri.getHost());
            values.put(COMPONENT, intent.getComponent().flattenToString());

            if (alwaysCheck) {
                values.put(PREFERRED, true);
            }
            values.put(LAST_CHOSEN, true);
            getContentResolver().insert(CONTENT_URI, values);

            history.add(intent.getComponent().getPackageName());
        }
    }

    if (intent != null) {
        startActivity(intent);
    }
    history.save(this);
}

From source file:ja.ohac.wallet.ui.SendCoinsFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.send_coins_fragment, container);

    receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address);
    receivingAddressView.setAdapter(new AutoCompleteAddressAdapter(activity, null));
    receivingAddressView.setOnFocusChangeListener(receivingAddressListener);
    receivingAddressView.addTextChangedListener(receivingAddressListener);

    receivingStaticView = view.findViewById(R.id.send_coins_receiving_static);
    receivingStaticAddressView = (TextView) view.findViewById(R.id.send_coins_receiving_static_address);
    receivingStaticLabelView = (TextView) view.findViewById(R.id.send_coins_receiving_static_label);

    receivingStaticView.setOnFocusChangeListener(new OnFocusChangeListener() {
        private ActionMode actionMode;

        @Override/* www .  j  a v a2 s.c  o m*/
        public void onFocusChange(final View v, final boolean hasFocus) {
            if (hasFocus)
                actionMode = activity.startActionMode(new ReceivingAddressActionMode());
            else
                actionMode.finish();
        }
    });

    final CurrencyAmountView btcAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount_btc);
    btcAmountView.setCurrencySymbol(btcShift == 0 ? Constants.CURRENCY_CODE_BTC : Constants.CURRENCY_CODE_MBTC);
    btcAmountView.setInputPrecision(btcShift == 0 ? Constants.BTC_MAX_PRECISION : Constants.MBTC_MAX_PRECISION);
    btcAmountView.setHintPrecision(btcPrecision);
    btcAmountView.setShift(btcShift);

    final CurrencyAmountView localAmountView = (CurrencyAmountView) view
            .findViewById(R.id.send_coins_amount_local);
    localAmountView.setInputPrecision(Constants.LOCAL_PRECISION);
    localAmountView.setHintPrecision(Constants.LOCAL_PRECISION);
    amountCalculatorLink = new CurrencyCalculatorLink(btcAmountView, localAmountView);

    bluetoothEnableView = (CheckBox) view.findViewById(R.id.send_coins_bluetooth_enable);
    bluetoothEnableView.setChecked(bluetoothAdapter != null && bluetoothAdapter.isEnabled());
    bluetoothEnableView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            if (isChecked && !bluetoothAdapter.isEnabled()) {
                // try to enable bluetooth
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
                        REQUEST_CODE_ENABLE_BLUETOOTH);
            }
        }
    });

    bluetoothMessageView = (TextView) view.findViewById(R.id.send_coins_bluetooth_message);

    sentTransactionView = (ListView) view.findViewById(R.id.send_coins_sent_transaction);
    sentTransactionListAdapter = new TransactionsListAdapter(activity, wallet, application.maxConnectedPeers(),
            false);
    sentTransactionView.setAdapter(sentTransactionListAdapter);

    viewGo = (Button) view.findViewById(R.id.send_coins_go);
    viewGo.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            validateReceivingAddress(true);
            validateAmounts(true);

            if (everythingValid())
                handleGo();
        }
    });

    viewCancel = (Button) view.findViewById(R.id.send_coins_cancel);
    viewCancel.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (state == State.INPUT)
                activity.setResult(Activity.RESULT_CANCELED);

            activity.finish();
        }
    });

    popupMessageView = (TextView) inflater.inflate(R.layout.send_coins_popup_message, container);

    popupAvailableView = inflater.inflate(R.layout.send_coins_popup_available, container);

    if (savedInstanceState != null) {
        restoreInstanceState(savedInstanceState);
    } else {
        final Intent intent = activity.getIntent();
        final String action = intent.getAction();
        final Uri intentUri = intent.getData();
        final String scheme = intentUri != null ? intentUri.getScheme() : null;

        if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && intentUri != null && "sakuracoin".equals(scheme))
            initStateFromBitcoinUri(intentUri);
        else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_ADDRESS))
            initStateFromIntentExtras(intent.getExtras());
    }

    return view;
}

From source file:com.baroq.pico.google.PlayServices.java

@Override
public void onLeaderboardScoresLoaded(int statusCode, LeaderboardBuffer leaderboard,
        LeaderboardScoreBuffer scores) {
    JSONObject json = new JSONObject();
    try {/*from  w ww.jav a  2s  .  co m*/
        json.put("type", GAME_LEADERBOARD_SCORES_LOADED);
        json.put("statusCode", statusCode);
        switch (statusCode) {
        case GamesClient.STATUS_OK:
            // if data was successfully loaded and is up-to-date.
            JSONArray list = new JSONArray();
            JSONObject obj;
            JSONArray vList;
            JSONObject v;
            Leaderboard lb;
            ArrayList<LeaderboardVariant> variants;
            LeaderboardVariant variant;
            int i, l, j, k;
            for (i = 0, l = leaderboard.getCount(); i < l; i++) {
                obj = new JSONObject();
                lb = leaderboard.get(i);
                obj.put("displayName", lb.getDisplayName());
                Uri uri = lb.getIconImageUri();
                if (null != uri)
                    obj.put("iconImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart());
                obj.put("leaderboardId", lb.getLeaderboardId());
                obj.put("scoreOrder", lb.getScoreOrder());
                variants = lb.getVariants();
                vList = new JSONArray();
                for (j = 0, k = variants.size(); j < k; j++) {
                    v = new JSONObject();
                    variant = variants.get(i);
                    v.put("collection", variant.getCollection());
                    v.put("numScores", variant.getNumScores());
                    v.put("timeSpan", variant.getTimeSpan());
                    v.put("hasPlayerInfo", variant.hasPlayerInfo());
                    if (variant.hasPlayerInfo()) {
                        v.put("displayPlayerRank", variant.getDisplayPlayerRank());
                        v.put("displayPlayerScore", variant.getDisplayPlayerScore());
                        v.put("playerRank", variant.getPlayerRank());
                        v.put("rawPlayerScore", variant.getRawPlayerScore());
                    }
                    vList.put(v);
                    obj.put("variants", vList);
                }
                list.put(obj);
            }
            json.put("leaderboard", list);
            LeaderboardScore lbs;
            for (i = 0, l = scores.getCount(); i < l; i++) {
                obj = new JSONObject();
                lbs = scores.get(i);
                obj.put("displayRank", lbs.getDisplayRank());
                obj.put("displayScore", lbs.getDisplayScore());
                obj.put("rank", lbs.getRank());
                obj.put("rawScore", lbs.getRawScore());
                obj.put("scoreHolderPlayerId", lbs.getScoreHolder().getPlayerId());
                obj.put("scoreHolderDisplayName", lbs.getScoreHolderDisplayName());
                Uri uri = lbs.getScoreHolderHiResImageUri();
                if (null != uri)
                    obj.put("scoreHolderHiResImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart());
                uri = lbs.getScoreHolderIconImageUri();
                if (null != uri)
                    obj.put("scoreHolderIconImageUri", uri.getScheme() + ':' + uri.getSchemeSpecificPart());
                obj.put("timestampMillis", lbs.getTimestampMillis());
                list.put(obj);
            }
            json.put("scores", list);
            break;
        case GamesClient.STATUS_INTERNAL_ERROR:
            // if an unexpected error occurred in the service 
            break;
        case GamesClient.STATUS_NETWORK_ERROR_STALE_DATA:
            // if the device was unable to communicate with the network. in this case, the operation is not retried automatically.
            break;
        case GamesClient.STATUS_CLIENT_RECONNECT_REQUIRED:
            // need to reconnect GamesClient
            mHelper.reconnectClients(clientTypes);
            break;
        case GamesClient.STATUS_LICENSE_CHECK_FAILED:
            // the game is not licensed to the user. further calls will return the same code.
            break;
        default:
            // error
            break;
        }
    } catch (JSONException ex) {
        Log.e(TAG, "game_leaderboard_scores_loaded [" + statusCode + "] exception: " + ex.getMessage());
        return;
    }

    leaderboard.close();
    scores.close();
    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, json);
    pluginResult.setKeepCallback(true);
    connectionCB.sendPluginResult(pluginResult);
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuActivity.java

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (resultCode != RESULT_OK)
        return;/* www . j a v a  2 s.  c o m*/

    switch (requestCode) {
    case SELECT_FILE_REQ:
        // clear previous data
        mFilePath = null;
        mFileStreamUri = null;

        // and 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 if 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);
            mFilePath = path;

            mFileNameView.setText(file.getName());
            mFileSizeView.setText(getString(R.string.dfu_file_size_text, file.length()));
            final boolean isHexFile = mStatusOk = MimeTypeMap.getFileExtensionFromUrl(path)
                    .equalsIgnoreCase("HEX");
            mFileStatusView.setText(isHexFile ? R.string.dfu_file_status_ok : R.string.dfu_file_status_invalid);
            mUploadButton.setEnabled(mSelectedDevice != null && isHexFile);
        } else if (uri.getScheme().equals("content")) {
            // an Uri has been returned
            mFileStreamUri = uri;
            // if application returned Uri for streaming, let's us 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))
                mFileStreamUri = 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);
            getSupportLoaderManager().restartLoader(0, bundle, this);
        }
        break;
    default:
        break;
    }
}

From source file:Main.java

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

    return null;
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

private String getRealPathFromURI(Uri contentUri, CordovaInterface cordova) {
    final String scheme = contentUri.getScheme();

    if (scheme.compareTo("content") == 0) {
        String[] proj = { "_data" };
        Cursor cursor = cordova.getActivity().managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow("_data");
        cursor.moveToFirst();//from   w  ww.ja  v a2 s .c o  m
        return cursor.getString(column_index);
    } else if (scheme.compareTo("file") == 0) {
        return contentUri.getPath();
    } else {
        return contentUri.toString();
    }
}

From source file:com.remobile.filetransfer.FileTransfer.java

/**
 * Downloads a file form a given URL and saves it to the specified directory.
 *
 * @param source URL of the server to receive the file
 * @param target Full path of the file on the file system
 *//*from  w ww.  j a  va 2  s  .  c om*/
private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "download " + source + " to " + target);
    final CordovaResourceApi resourceApi = new CordovaResourceApi(getReactApplicationContext());

    final boolean trustEveryone = args.optBoolean(2);
    final String objectId = args.getString(3);
    final JSONObject headers = args.optJSONObject(4);

    final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));

    // Accept a path or a URI for the source.
    Uri tmpTarget = Uri.parse(target);
    final Uri targetUri = resourceApi
            .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));

    int uriType = CordovaResourceApi.getUriType(sourceUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
    if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
        Log.e(LOG_TAG, "Unsupported URI: " + sourceUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection connection = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            File file = null;
            PluginResult result = null;
            TrackingInputStream inputStream = null;
            boolean cached = false;

            OutputStream outputStream = null;
            try {
                CordovaResourceApi.OpenForReadResult readResult = null;

                file = resourceApi.mapUriToFile(targetUri);
                context.targetFile = file;

                Log.d(LOG_TAG, "Download file:" + sourceUri);

                FileProgressResult progress = new FileProgressResult();

                if (isLocalTransfer) {
                    readResult = resourceApi.openForRead(sourceUri);
                    if (readResult.length != -1) {
                        progress.setLengthComputable(true);
                        progress.setTotal(readResult.length);
                    }
                    inputStream = new SimpleTrackingInputStream(readResult.inputStream);
                } else {
                    // connect to server
                    // Open a HTTP connection to the URL based on protocol
                    connection = resourceApi.createHttpConnection(sourceUri);
                    if (useHttps && trustEveryone) {
                        // Setup the HTTPS connection class to trust everyone
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        oldSocketFactory = trustAllHosts(https);
                        // Save the current hostnameVerifier
                        oldHostnameVerifier = https.getHostnameVerifier();
                        // Setup the connection not to verify hostnames
                        https.setHostnameVerifier(DO_NOT_VERIFY);
                    }

                    connection.setRequestMethod("GET");

                    // This must be explicitly set for gzip progress tracking to work.
                    connection.setRequestProperty("Accept-Encoding", "gzip");

                    // Handle the other headers
                    if (headers != null) {
                        addHeadersToRequest(connection, headers);
                    }

                    connection.connect();
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        cached = true;
                        connection.disconnect();
                        Log.d(LOG_TAG, "Resource not modified: " + source);
                        JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection,
                                null);
                        result = new PluginResult(PluginResult.Status.ERROR, error);
                    } else {
                        if (connection.getContentEncoding() == null
                                || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                            // Only trust content-length header if we understand
                            // the encoding -- identity or gzip
                            if (connection.getContentLength() != -1) {
                                progress.setLengthComputable(true);
                                progress.setTotal(connection.getContentLength());
                            }
                        }
                        inputStream = getInputStream(connection);
                    }
                }

                if (!cached) {
                    try {
                        synchronized (context) {
                            if (context.aborted) {
                                return;
                            }
                            context.connection = connection;
                        }

                        // write bytes to file
                        byte[] buffer = new byte[MAX_BUFFER_SIZE];
                        int bytesRead = 0;
                        outputStream = resourceApi.openOutputStream(targetUri);
                        while ((bytesRead = inputStream.read(buffer)) > 0) {
                            outputStream.write(buffer, 0, bytesRead);
                            // Send a progress event.
                            progress.setLoaded(inputStream.getTotalRawBytesRead());
                            FileTransfer.this.sendJSEvent("DownloadProgress-" + objectId,
                                    JsonConvert.jsonToReact(progress.toJSONObject()));
                        }
                    } finally {
                        synchronized (context) {
                            context.connection = null;
                        }
                        safeClose(inputStream);
                        safeClose(outputStream);
                    }

                    Log.d(LOG_TAG, "Saved file: " + target);

                    file = resourceApi.mapUriToFile(targetUri);
                    context.targetFile = file;
                    result = new PluginResult(PluginResult.Status.OK, targetUri.getPath());
                }

            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
            } catch (Throwable e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (connection != null) {
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }

                if (result == null) {
                    result = new PluginResult(PluginResult.Status.ERROR,
                            createFileTransferError(CONNECTION_ERR, source, target, connection, null));
                }
                // Remove incomplete download.
                if (!cached && result.status.ordinal() != PluginResult.Status.OK.ordinal() && file != null) {
                    file.delete();
                }
                context.sendPluginResult(result);
            }
        }
    });
}

From source file:Main.java

@SuppressLint("NewApi")
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];
            }/*from  ww  w.j  a v  a  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 null;
}

From source file:com.xorcode.andtweet.PreferencesActivity.java

@Override
protected void onResume() {
    super.onResume();

    // Stop service to force preferences reload on the next start
    // Plus disable repeating alarms for awhile (till next start service...)
    AndTweetServiceManager.stopAndTweetService(this, true);

    showAllPreferences();//w  ww.  j  a  v  a2  s .co  m
    MyPreferences.getDefaultSharedPreferences().registerOnSharedPreferenceChangeListener(this);

    Uri uri = getIntent().getData();
    if (uri != null) {
        if (MyLog.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "uri=" + uri.toString());
        }
        if (CALLBACK_URI.getScheme().equals(uri.getScheme())) {
            // To prevent repeating of this task
            getIntent().setData(null);
            // This activity was started by Twitter ("Service Provider")
            // so start second step of OAuth Authentication process
            new OAuthAcquireAccessTokenTask().execute(uri);
            // and return back to default screen
            overrideBackButton = true;
        }
    }
}

From source file:Main.java

/**
 * Get the file path from the given Uri.
 *
 * @param context The context of the calling activity.
 * @param uri     The Uri whose file path is returned.
 */// w  w  w .  j  ava  2  s .c  o  m
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getFilePathFromUri(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];
            }
        }
        // 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;
}