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.brandroidtools.filemanager.activities.PickerActivity.java

private boolean isFilePickIntent(Intent intent) {
    final String action = intent.getAction();

    if (Intent.ACTION_GET_CONTENT.equals(action)) {
        return true;
    }//from   www.java2  s  . c  om
    if (Intent.ACTION_PICK.equals(action)) {
        final Uri data = intent.getData();
        if (data != null && FILE_URI_SCHEME.equals(data.getScheme())) {
            return true;
        }
    }

    return false;
}

From source file:net.sf.asap.PlayerService.java

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    registerMediaButtonEventReceiver("registerMediaButtonEventReceiver");

    TelephonyManager telephony = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    telephony.listen(new PhoneStateListener() {
        public void onCallStateChanged(int state, String incomingNumber) {
            if (state == TelephonyManager.CALL_STATE_RINGING)
                pause();//from w  w  w  .jav  a  2s .c  o  m
        }
    }, PhoneStateListener.LISTEN_CALL_STATE);

    Uri uri = intent.getData();
    String playlistUri = intent.getStringExtra(EXTRA_PLAYLIST);
    if (playlistUri != null)
        setPlaylist(Uri.parse(playlistUri), false);
    else if ("file".equals(uri.getScheme())) {
        if (ASAPInfo.isOurFile(uri.toString()))
            setPlaylist(Util.getParent(uri), false);
        else {
            setPlaylist(uri, true);
            uri = playlist.get(0);
        }
    }
    playFile(uri, SONG_DEFAULT);
}

From source file:moose.com.ac.ArticleViewActivity.java

private void filterImg(String str) {
    Document mDocument = Jsoup.parse(str);

    Elements imgs = mDocument.select("img");
    for (int imgIndex = 0; imgIndex < imgs.size(); imgIndex++) {
        Element img = imgs.get(imgIndex);
        String src = img.attr("src").trim();
        if (TextUtils.isEmpty(src))
            continue;
        Uri parsedUri = Uri.parse(src);
        if ("file".equals(parsedUri.getScheme()))
            continue;
        if (parsedUri.getPath() == null)
            continue;
        if (!"http".equals(parsedUri.getScheme())) {
            parsedUri = parsedUri.buildUpon().scheme("http").authority("www.acfun.tv").build();
        }//w  w  w .j a v  a 2 s . com
        // url may have encoded path
        parsedUri = parsedUri.buildUpon().path(parsedUri.getPath()).build();
        src = parsedUri.toString();
        Log.i(TAG, "image src:" + src);
        img.attr("org", src);
        if (CommonUtil.getMode() == 1 && !CommonUtil.isWifiConnected(mContext)) {//
            Log.i(TAG, "[?]");
            img.after("<div style=\"width: 100%;text-align: center;\"><br><p>[]</p></div>");
        } else {
            Log.i(TAG, "[?]");
            StringBuilder builder = new StringBuilder();
            builder.append("<div style='text-align: center;'><br>")
                    .append("<img src='file:///android_asset/loading.gif'").append("name = '").append(src)
                    .append("'\n;onclick = window.JsBridge.showImage('").append(src).append("')")
                    .append(" alt=' '/>\n").append("</div>");
            img.after(builder.toString());
            Log.i(TAG, "image:table:-" + builder.toString());
        }
        /*if (CommonUtil.getMode() == 1 && !CommonUtil.isWifiConnected(mContext)) {
        img.after("<p >[]</p>");
        } else if (!src.contains(Config.AC_EMOTION)) {
        StringBuilder builder = new StringBuilder();
        builder.append("<div style=\"width: 100%;text-align: center;\"><br><img src=\"")
                .append(src)
                .append("\" width=: 100%;height:auto\"")
                .append(" alt=\" \"/>\n")
                .append("</div>");
        Log.i(TAG, "index image:" + builder.toString());
        img.after(builder.toString());
        } else {
        img.after("<img src=\"" + src + "\" alt=\" \"/>\n");
        }*/

        img.remove();
        //img.removeAttr("style");
        HtmlBody = mDocument.toString();
        Log.i(TAG, "??html:" + HtmlBody);
    }
}

From source file:nl.sogeti.android.gpstracker.viewer.TrackList.java

private void displayIntent(Intent intent) {
    final String queryAction = intent.getAction();
    final String orderby = Tracks.CREATION_TIME + " DESC";
    Cursor tracksCursor = null;// w  ww  . ja  v a  2 s  . c o  m
    if (Intent.ACTION_SEARCH.equals(queryAction)) {
        // Got to SEARCH a query for tracks, make a list
        tracksCursor = doSearchWithIntent(intent);
    } else if (Intent.ACTION_VIEW.equals(queryAction)) {
        final Uri uri = intent.getData();
        if ("content".equals(uri.getScheme()) && GPStracking.AUTHORITY.equals(uri.getAuthority())) {
            // Got to VIEW a single track, instead hand it of to the LoggerMap
            Intent notificationIntent = new Intent(this, LoggerMap.class);
            notificationIntent.setData(uri);
            startActivity(notificationIntent);
            finish();
        } else if (uri.getScheme().equals("file") || uri.getScheme().equals("content")) {

            mImportTrackName = uri.getLastPathSegment();
            // Got to VIEW a GPX filename
            mImportAction = new Runnable() {
                @Override
                public void run() {
                    new GpxParser(TrackList.this, TrackList.this).execute(uri);
                }
            };
            showDialog(DIALOG_IMPORT);
            tracksCursor = managedQuery(Tracks.CONTENT_URI,
                    new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, orderby);
        } else {
            Log.e(this, "Unable to VIEW " + uri);
        }
    } else {
        // Got to nothing, make a list of everything
        tracksCursor = managedQuery(Tracks.CONTENT_URI,
                new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, orderby);
    }
    displayCursor(tracksCursor);

}

From source file:com.android.messaging.mmslib.pdu.PduPersister.java

/**
 * This method expects uri in the following format
 *     content://media/<table_name>/<row_index> (or)
 *     file://sdcard/test.mp4/*from  w ww.  j a va 2  s . co m*/
 *     http://test.com/test.mp4
 *
 * Here <table_name> shall be "video" or "audio" or "images"
 * <row_index> the index of the content in given table
 */
public static String convertUriToPath(final Context context, final Uri uri) {
    String path = null;
    if (null != uri) {
        final String scheme = uri.getScheme();
        if (null == scheme || scheme.equals("") || scheme.equals(ContentResolver.SCHEME_FILE)) {
            path = uri.getPath();

        } else if (scheme.equals("http")) {
            path = uri.toString();

        } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            final String[] projection = new String[] { MediaStore.MediaColumns.DATA };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) {
                    throw new IllegalArgumentException("Given Uri could not be found" + " in media store");
                }
                final int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                path = cursor.getString(pathIndex);
            } catch (final SQLiteException e) {
                throw new IllegalArgumentException(
                        "Given Uri is not formatted in a way " + "so that it can be found in media store.");
            } finally {
                if (null != cursor) {
                    cursor.close();
                }
            }
        } else {
            throw new IllegalArgumentException("Given Uri scheme is not supported");
        }
    }
    return path;
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private static String extractUrl(Uri uri) {
    String result = uri.getScheme() + "://" + uri.getAuthority() + uri.getPath();
    String fragment = uri.getFragment();
    if (fragment != null) {
        result += "#" + fragment;
    }// w w w. ja va 2 s . c o m
    return result;
}

From source file:com.keepassdroid.fileselect.FileSelectActivity.java

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

    fileHistory = App.getFileHistory();/*from w  w  w . j a  va2  s . c o  m*/

    if (fileHistory.hasRecentFiles()) {
        recentMode = true;
        setContentView(R.layout.file_selection);
    } else {
        setContentView(R.layout.file_selection_no_recent);
    }

    mList = (ListView) findViewById(R.id.file_list);

    mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            onListItemClick((ListView) parent, v, position, id);
        }
    });

    // Open button
    Button openButton = (Button) findViewById(R.id.open);
    openButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            String fileName = Util.getEditText(FileSelectActivity.this, R.id.file_filename);

            try {
                PasswordActivity.Launch(FileSelectActivity.this, fileName);
            } catch (ContentFileNotFoundException e) {
                Toast.makeText(FileSelectActivity.this, R.string.file_not_found_content, Toast.LENGTH_LONG)
                        .show();
            } catch (FileNotFoundException e) {
                Toast.makeText(FileSelectActivity.this, R.string.FileNotFound, Toast.LENGTH_LONG).show();
            }

        }
    });

    // Create button
    Button createButton = (Button) findViewById(R.id.create);
    createButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            String filename = Util.getEditText(FileSelectActivity.this, R.id.file_filename);

            // Make sure file name exists
            if (filename.length() == 0) {
                Toast.makeText(FileSelectActivity.this, R.string.error_filename_required, Toast.LENGTH_LONG)
                        .show();
                return;
            }

            // Try to create the file
            File file = new File(filename);
            try {
                if (file.exists()) {
                    Toast.makeText(FileSelectActivity.this, R.string.error_database_exists, Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                File parent = file.getParentFile();

                if (parent == null || (parent.exists() && !parent.isDirectory())) {
                    Toast.makeText(FileSelectActivity.this, R.string.error_invalid_path, Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                if (!parent.exists()) {
                    // Create parent dircetory
                    if (!parent.mkdirs()) {
                        Toast.makeText(FileSelectActivity.this, R.string.error_could_not_create_parent,
                                Toast.LENGTH_LONG).show();
                        return;

                    }
                }

                file.createNewFile();
            } catch (IOException e) {
                Toast.makeText(FileSelectActivity.this,
                        getText(R.string.error_file_not_create) + " " + e.getLocalizedMessage(),
                        Toast.LENGTH_LONG).show();
                return;
            }

            // Prep an object to collect a password once the database has
            // been created
            CollectPassword password = new CollectPassword(new LaunchGroupActivity(filename));

            // Create the new database
            CreateDB create = new CreateDB(FileSelectActivity.this, filename, password, true);
            ProgressTask createTask = new ProgressTask(FileSelectActivity.this, create,
                    R.string.progress_create);
            createTask.run();

        }

    });

    ImageButton browseButton = (ImageButton) findViewById(R.id.browse_button);
    browseButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (StorageAF.useStorageFramework(FileSelectActivity.this)) {
                Intent i = new Intent(StorageAF.ACTION_OPEN_DOCUMENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                startActivityForResult(i, OPEN_DOC);
            } else {
                Intent i;
                i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");

                try {
                    startActivityForResult(i, GET_CONTENT);
                } catch (ActivityNotFoundException e) {
                    lookForOpenIntentsFilePicker();
                } catch (SecurityException e) {
                    lookForOpenIntentsFilePicker();
                }
            }
        }

        private void lookForOpenIntentsFilePicker() {

            if (Interaction.isIntentAvailable(FileSelectActivity.this, Intents.OPEN_INTENTS_FILE_BROWSE)) {
                Intent i = new Intent(Intents.OPEN_INTENTS_FILE_BROWSE);
                i.setData(Uri.parse("file://" + Util.getEditText(FileSelectActivity.this, R.id.file_filename)));
                try {
                    startActivityForResult(i, FILE_BROWSE);
                } catch (ActivityNotFoundException e) {
                    showBrowserDialog();
                }

            } else {
                showBrowserDialog();
            }
        }

        private void showBrowserDialog() {
            BrowserDialog diag = new BrowserDialog(FileSelectActivity.this);
            diag.show();
        }
    });

    fillData();

    registerForContextMenu(mList);

    // Load default database
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String fileName = prefs.getString(PasswordActivity.KEY_DEFAULT_FILENAME, "");

    if (fileName.length() > 0) {
        Uri dbUri = UriUtil.parseDefaultFile(fileName);
        String scheme = dbUri.getScheme();

        if (!EmptyUtils.isNullOrEmpty(scheme) && scheme.equalsIgnoreCase("file")) {
            String path = dbUri.getPath();
            File db = new File(path);

            if (db.exists()) {
                try {
                    PasswordActivity.Launch(FileSelectActivity.this, path);
                } catch (Exception e) {
                    // Ignore exception
                }
            }
        } else {
            try {
                PasswordActivity.Launch(FileSelectActivity.this, dbUri.toString());
            } catch (Exception e) {
                // Ignore exception
            }
        }
    }
}

From source file:co.codecrunch.musicplayerlite.activities.MusicPlayerBaseActivity.java

/**
 * Get intent data from music choose option
 *//*w w w .j a  v a2  s .  co  m*/
private void getIntentData() {
    try {
        Uri data = getIntent().getData();
        if (data != null) {
            if (data.getScheme().equalsIgnoreCase("file")) {
                String path = data.getPath().toString();
                if (!TextUtils.isEmpty(path)) {
                    MediaController.getInstance().cleanupPlayer(context, true, true);
                    MusicPreferance.getPlaylist(context, path);
                    updateTitle(false);
                    MediaController.getInstance().playAudio(MusicPreferance.playingSongDetail);
                    mLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
                }
            }
            if (data.getScheme().equalsIgnoreCase("http"))
                LogWriter.info(TAG, data.getPath().toString());
            if (data.getScheme().equalsIgnoreCase("content"))
                LogWriter.info(TAG, data.getPath().toString());

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.frostwire.android.gui.transfers.TransferManager.java

public BittorrentDownload downloadTorrent(String uri, TorrentFetcherListener fetcherListener,
        String tempDownloadTitle) {
    String url = uri.trim();//ww  w  . jav  a2  s.  c  om
    try {
        if (url.contains("urn%3Abtih%3A")) {
            //fixes issue #129: over-encoded url coming from intent
            url = url.replace("urn%3Abtih%3A", "urn:btih:");
        }

        if (isAlreadyDownloadingTorrentByUri(url)) {
            return null;
        }

        Uri u = Uri.parse(url);
        String scheme = u.getScheme();
        if (!scheme.equalsIgnoreCase("file") && !scheme.equalsIgnoreCase("http")
                && !scheme.equalsIgnoreCase("https") && !scheme.equalsIgnoreCase("magnet")) {
            LOG.warn("Invalid URI scheme: " + u.toString());
            return new InvalidBittorrentDownload(R.string.torrent_scheme_download_not_supported);
        }

        BittorrentDownload download = null;

        if (fetcherListener == null) {
            if (scheme.equalsIgnoreCase("file")) {
                BTEngine.getInstance().download(new File(u.getPath()), null, null);
            } else if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")
                    || scheme.equalsIgnoreCase("magnet")) {
                download = new TorrentFetcherDownload(this,
                        new TorrentUrlInfo(u.toString(), tempDownloadTitle));
                bittorrentDownloadsList.add(download);
                bittorrentDownloadsMap.put(download.getInfoHash(), download);
            }
        } else {
            if (scheme.equalsIgnoreCase("file")) {
                fetcherListener.onTorrentInfoFetched(FileUtils.readFileToByteArray(new File(u.getPath())), null,
                        -1);
            } else if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")
                    || scheme.equalsIgnoreCase("magnet")) {
                // this executes the listener method when it fetches the bytes.
                download = new TorrentFetcherDownload(this, new TorrentUrlInfo(u.toString(), tempDownloadTitle),
                        fetcherListener);
                bittorrentDownloadsList.add(download);
                bittorrentDownloadsMap.put(download.getInfoHash(), download);
                incrementStartedTransfers();
                return download;
            }
            return null;
        }

        incrementStartedTransfers();
        return download;
    } catch (Throwable e) {
        LOG.warn("Error creating download from uri: " + url, e);
        return new InvalidBittorrentDownload(R.string.torrent_scheme_download_not_supported);
    }
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private InputStream getInputStream(Uri mUri) throws IOException {
    try {/*from  w w  w  .j  a va 2  s.  c om*/
        if (mUri.getScheme().equals("file")) {
            return new java.io.FileInputStream(mUri.getPath());
        } else {
            return getContext().getContentResolver().openInputStream(mUri);
        }
    } catch (FileNotFoundException ex) {
        return null;
    }
}