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:net.sourceforge.servestream.fragment.AddUrlFragment.java

private void processUri() {
    String input = mUrlEditText.getText().toString();

    Uri uri = TransportFactory.getUri(input);

    if (uri == null) {
        mUrlEditText.setError(getString(R.string.error_url_label));
        return;//from w  ww.  j ava 2 s .co  m
    }

    StreamDatabase streamdb = new StreamDatabase(getActivity());
    UriBean uriBean = TransportFactory.findUri(streamdb, uri);
    if (uriBean == null) {
        uriBean = TransportFactory.getTransport(uri.getScheme()).createUri(uri);

        if (mSavePlaylistEntriesCheckbox.isChecked()) {
            streamdb.close();
            new ParseEntriesTask(getActivity(), mHandler, uriBean).execute();
            return;
        } else {
            String nickname = mNicknameEditText.getText().toString();

            if (!nickname.equals("")) {
                uriBean.setNickname(nickname);
            }

            AbsTransport transport = TransportFactory.getTransport(uriBean.getProtocol());
            transport.setUri(uriBean);
            streamdb.saveUri(uriBean);
        }
    }

    streamdb.close();

    Intent intent = new Intent(getActivity(), MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    getActivity().finish();
}

From source file:nz.ac.auckland.lablet.script.ScriptRunnerActivity.java

@Nullable
private String computeFileName(@NonNull Uri uri) {

    // 'content' scheme will include the file name in the meta data
    if (uri.getScheme().equals("content")) {

        // open the Uri meta data so we can read the file name
        final String[] nameProjection = { MediaColumns.DISPLAY_NAME };
        Cursor uriMetaData = getContentResolver().query(uri, nameProjection, null, null, null);
        if (uriMetaData == null) {
            return null;
        }/* w ww .ja v a 2  s .c  o m*/

        // move to first row of uri meta data and read display name, return if this fails
        final int displayName = 0;
        try {
            return uriMetaData.moveToFirst() ? uriMetaData.getString(displayName) : null;
        } finally {
            uriMetaData.close();
        }
    }

    // 'file' scheme will have the file name stored in the path
    if (uri.getScheme().equals("file")) {
        return uri.getLastPathSegment();
    }

    // unsupported scheme
    return null;
}

From source file:com.cyanogenmod.messaging.quickmessage.QuickMessagePopup.java

/**
 * display the sim select dialog for multi sim phones
 *///  w  w  w  . ja  va2 s.co  m
private void showSimSelector(Activity activity, final ComposeMessageView.OnSimSelectedCallback cb) {
    final TelecomManager telecomMgr = (TelecomManager) activity.getSystemService(Context.TELECOM_SERVICE);
    final List<PhoneAccountHandle> handles = telecomMgr.getCallCapablePhoneAccounts();
    final List<PhoneAccountHandle> filteredHandles = new ArrayList<>();

    //trim out SIP accounts
    for (PhoneAccountHandle handle : handles) {
        PhoneAccount phoneAccount = PhoneUtils.getAccountOrNull(activity, handle);
        if (phoneAccount != null) {
            Uri address = phoneAccount.getAddress();
            if (address != null && !TextUtils.equals(address.getScheme(), PhoneAccount.SCHEME_SIP)) {
                filteredHandles.add(handle);
            }
        }
    }

    final SelectPhoneAccountDialogFragment.SelectPhoneAccountListener listener = new SelectPhoneAccountDialogFragment.SelectPhoneAccountListener() {
        @Override
        public void onPhoneAccountSelected(PhoneAccountHandle selectedAccountHandle, boolean setDefault) {
            // we need the subId and we only have a PhoneAccountHandle
            TelephonyManager telephonyManager = (TelephonyManager) mContext
                    .getSystemService(Context.TELEPHONY_SERVICE);
            Iterator<PhoneAccountHandle> phoneAccounts = telecomMgr.getCallCapablePhoneAccounts()
                    .listIterator();
            int subId = 0; // defaulting to 0, just in case
            while (phoneAccounts.hasNext()) {
                PhoneAccountHandle p = phoneAccounts.next();
                if (p.getId().equals(selectedAccountHandle.getId())) {
                    PhoneAccount phoneAccount = telecomMgr.getPhoneAccount(p);
                    subId = telephonyManager.getSubIdForPhoneAccount(phoneAccount);
                }
            }
            cb.onSimSelected(subId);
        }

        @Override
        public void onDialogDismissed() {
        }
    };

    DialogFragment dialogFragment = SelectPhoneAccountDialogFragment.newInstance(
            R.string.select_phone_account_title, false /* canSetDefault */, filteredHandles, listener);
    dialogFragment.show(activity.getFragmentManager(), "SELECT_PHONE_ACCOUNT_DIALOG_FRAGMENT");
}

From source file:com.dosse.bwentrain.androidPlayer.MainActivity.java

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    new AdsController().start();
    try {/*from  www  .ja v a  2s  .c  o  m*/
        if (getIntent().getData() != null) { //called from an url
            Uri u = getIntent().getData();
            if (u == null)
                throw new Exception();
            String url = u.getScheme() + ":" + u.getEncodedSchemeSpecificPart();
            if (url.toLowerCase().startsWith("http://sine.adolfintel.com/forum")
                    || url.toLowerCase().startsWith("http://isochronic.io/forum"))
                startActivity(new Intent(this, CommunityActivity.class).putExtra("path", url)); //throw the url to the community activity
            else if (url.toLowerCase().startsWith("http://sine.adolfintel.com/goto.php")
                    || url.toLowerCase().startsWith("http://sine.adolfintel.com/presets.php")
                    || url.toLowerCase().startsWith("http://isochronic.io/goto.php")
                    || url.toLowerCase().startsWith("http://isochronic.io/presets.php")) { //link to a preset, or to the preset page
                //attempt to convert to mobile and localized link
                try {
                    String newUrl = getString(R.string.presets_url);
                    //find preset id (if present) and add it to the new url
                    String q = new URL(url).getQuery();
                    if (q != null) {
                        String[] query = q.split("\\?");
                        for (String s : query) {
                            String[] ss = s.split("=");
                            if (ss[0].trim().equalsIgnoreCase("id")) {
                                newUrl += "%26id=" + Integer.parseInt(ss[1].trim());
                                break;
                            }
                        }
                    }
                    Intent i = new Intent(this, BrowserActivity.class);
                    i.putExtra("path", newUrl);
                    startActivity(i);
                } catch (Throwable t) {
                    Toast.makeText(getApplicationContext(), getString(R.string.community_invalid_presetId),
                            Toast.LENGTH_SHORT).show();
                }
            } else
                throw new Exception(); //ignore unknown urls
        } else
            throw new Exception();
    } catch (Throwable t) {
    }
    try {
        openFileInput("material.run");
        //material.run exists, go straight to the app
    } catch (Throwable t) {
        Intent i = new Intent(MainActivity.this, IntroActivity.class);
        try {
            openFileInput("first.run");
            //first.run exists, the user just updated the app to the material design version, show update intro
            i.putExtra("update", true);
        } catch (Throwable t1) {
            //first.run does not exist, show intro
            i.putExtra("update", false);
        }
        startActivity(i);
        try {
            openFileOutput("material.run", MODE_PRIVATE).close();
        } catch (Throwable t1) {
        }
    }
    super.onPostCreate(savedInstanceState);
}

From source file:com.xabber.android.ui.ContactList.java

@Override
protected void onResume() {
    super.onResume();
    barPainter.setDefaultColor();/*  w w w  .  j a v  a 2  s.com*/
    rebuildAccountToggle();
    Application.getInstance().addUIListener(OnAccountChangedListener.class, this);

    if (action != null) {
        switch (action) {
        case ContactList.ACTION_ROOM_INVITE:
        case Intent.ACTION_SEND:
        case Intent.ACTION_CREATE_SHORTCUT:
            if (Intent.ACTION_SEND.equals(action)) {
                sendText = getIntent().getStringExtra(Intent.EXTRA_TEXT);
            }
            Toast.makeText(this, getString(R.string.select_contact), Toast.LENGTH_LONG).show();
            break;
        case Intent.ACTION_VIEW: {
            action = null;
            Uri data = getIntent().getData();
            if (data != null && "xmpp".equals(data.getScheme())) {
                XMPPUri xmppUri;
                try {
                    xmppUri = XMPPUri.parse(data);
                } catch (IllegalArgumentException e) {
                    xmppUri = null;
                }
                if (xmppUri != null && "message".equals(xmppUri.getQueryType())) {
                    ArrayList<String> texts = xmppUri.getValues("body");
                    String text = null;
                    if (texts != null && !texts.isEmpty()) {
                        text = texts.get(0);
                    }
                    openChat(xmppUri.getPath(), text);
                }
            }
            break;
        }
        case Intent.ACTION_SENDTO: {
            action = null;
            Uri data = getIntent().getData();
            if (data != null) {
                String path = data.getPath();
                if (path != null && path.startsWith("/")) {
                    openChat(path.substring(1), null);
                }
            }
            break;
        }
        }
    }

    if (Application.getInstance().doNotify()) {
        if (!SettingsManager.isTranslationSuggested()) {
            Locale currentLocale = getResources().getConfiguration().locale;
            if (!currentLocale.getLanguage().equals("en") && !getResources().getBoolean(R.bool.is_translated)) {
                new TranslationDialog().show(getFragmentManager(), "TRANSLATION_DIALOG");
                SettingsManager.setTranslationSuggested();
            }
        }

        if (SettingsManager.bootCount() > 2 && !SettingsManager.connectionStartAtBoot()
                && !SettingsManager.startAtBootSuggested()) {
            StartAtBootDialogFragment.newInstance().show(getFragmentManager(), "START_AT_BOOT");
        }
        if (!SettingsManager.contactIntegrationSuggested() && Application.getInstance().isContactsSupported()) {
            if (AccountManager.getInstance().getAllAccounts().isEmpty()) {
                SettingsManager.setContactIntegrationSuggested();
            } else {
                ContactIntegrationDialogFragment.newInstance().show(getFragmentManager(),
                        "CONTACT_INTEGRATION");
            }
        }
    }
}

From source file:free.yhc.netmbuddy.model.NetLoader.java

public HttpRespContent getHttpContent(Uri uri, boolean source) throws LocalException {
    if (null == mHttpClient) {
        if (DBG)/*w ww . j a v a2 s .co m*/
            P.v("NetLoader Fail to get HttpClient");
        throw new LocalException(Err.UNKNOWN);
    }

    if (!Utils.isNetworkAvailable())
        throw new LocalException(Err.IO_NET);

    String uriString = uri.toString();
    if (source)
        uriString = uriString.replace(uri.getScheme() + "://" + uri.getHost(), "");

    int retry = Policy.NETOWRK_CONN_RETRY;
    while (0 < retry--) {
        try {
            HttpGet httpGet = new HttpGet(uriString);
            HttpHost httpTarget = new HttpHost(uri.getHost());

            if (DBG)
                P.v("executing request: " + httpGet.getRequestLine().toString());
            //logI("uri: " + httpGet.getURI().toString());
            //logI("target: " + httpTarget.getHostName());

            HttpResponse httpResp = mHttpClient.execute(httpTarget, httpGet);
            if (DBG)
                P.v("NetLoader HTTP response status line : " + httpResp.getStatusLine().toString());

            // TODO
            // Need more case-handling-code.
            // Ex. Redirection etc.
            int statusCode = httpResp.getStatusLine().getStatusCode();
            switch (statusCode) {
            case HttpUtils.SC_OK:
            case HttpUtils.SC_NO_CONTENT:
                ;// expected response. let's move forward
                break;

            default:
                // Unexpected response
                if (DBG)
                    P.w("Unexpected Response  status code : " + httpResp.getStatusLine().getStatusCode());
                throw new LocalException(Err.HTTPGET, statusCode);
            }

            InputStream contentStream = null;
            String contentType = null;
            if (HttpUtils.SC_NO_CONTENT == statusCode) {
                ;
            } else {
                HttpEntity httpEntity = httpResp.getEntity();

                if (null == httpEntity) {
                    if (DBG)
                        P.w("Unexpected NULL entity");
                    throw new LocalException(Err.HTTPGET, statusCode);
                }
                contentStream = httpEntity.getContent();
                try {
                    contentType = httpResp.getFirstHeader("Content-Type").getValue().toLowerCase();
                } catch (NullPointerException e) {
                    // Unexpected response data.
                    if (DBG)
                        P.v("NetLoader IOException : " + e.getMessage());
                    throw new LocalException(Err.IO_NET);
                }
            }

            return new HttpRespContent(statusCode, contentStream, contentType);
        } catch (ClientProtocolException e) {
            if (DBG)
                P.v("NetLoader ClientProtocolException : " + e.getMessage());
            throw new LocalException(Err.UNKNOWN);
        } catch (IllegalArgumentException e) {
            if (DBG)
                P.v("Illegal Argument Exception : " + e.getMessage() + "\n" + "URI : " + uriString);
            throw new LocalException(Err.IO_NET);
        } catch (UnknownHostException e) {
            if (DBG)
                P.v("NetLoader UnknownHostException : Maybe timeout?" + e.getMessage());
            if (mUserClose)
                throw new LocalException(Err.INTERRUPTED);

            if (0 >= retry)
                throw new LocalException(Err.IO_NET);

            ; // continue next retry after some time.
            try {
                Thread.sleep(300);
            } catch (InterruptedException ie) {
                throw new LocalException(Err.INTERRUPTED);
            }
            throw new LocalException(Err.IO_NET);
        } catch (IOException e) {
            if (DBG)
                P.v("NetLoader IOException : " + e.getMessage());
            throw new LocalException(Err.IO_NET);
        } catch (IllegalStateException e) {
            if (DBG)
                P.v("NetLoader IllegalStateException : " + e.getMessage());
            throw new LocalException(Err.UNKNOWN);
        }
    }
    eAssert(false);
    return null;
}

From source file:com.openerp.addons.messages.MessageComposeActivty.java

/**
 * getting real path from attachment URI.
 * //from   w w  w  . j  a  va2s .  co m
 * @param contentUri
 * @return
 */
private String getFilenameFromUri(Uri contentUri) {
    String filename = "unknown";
    if (contentUri.getScheme().toString().compareTo("content") == 0) {
        Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            filename = cursor.getString(column_index);
            File fl = new File(filename);
            filename = fl.getName();
        }
    } else if (contentUri.getScheme().compareTo("file") == 0) {
        filename = contentUri.getLastPathSegment().toString();
    } else {
        filename = filename + "_" + contentUri.getLastPathSegment();
    }
    return filename;
}

From source file:cm.aptoide.com.actionbarsherlock.widget.SuggestionsAdapter.java

/**
 * Gets a drawable by URI, without using the cache.
 *
 * @return A drawable, or {@code null} if the drawable could not be loaded.
 *//*  ww  w. j  av a 2  s .co m*/
private Drawable getDrawable(Uri uri) {
    try {
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            // Load drawables through Resources, to get the source density information
            try {
                return getTheDrawable(uri);
            } catch (Resources.NotFoundException ex) {
                throw new FileNotFoundException("Resource does not exist: " + uri);
            }
        } else {
            // Let the ContentResolver handle content and file URIs.
            InputStream stream = mProviderContext.getContentResolver().openInputStream(uri);
            if (stream == null) {
                throw new FileNotFoundException("Failed to open " + uri);
            }
            try {
                return Drawable.createFromStream(stream, null);
            } finally {
                try {
                    stream.close();
                } catch (IOException ex) {
                    Log.e(LOG_TAG, "Error closing icon stream for " + uri, ex);
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
        Log.w(LOG_TAG, "Icon not found: " + uri + ", " + fnfe.getMessage());
        return null;
    }
}

From source file:android.support.v7.widget.SuggestionsAdapter.java

/**
 * Gets a drawable by URI, without using the cache.
 *
 * @return A drawable, or {@code null} if the drawable could not be loaded.
 */// w  w  w  .  j a  v  a  2s.c  o m
private Drawable getDrawable(Uri uri) {
    try {
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            // Load drawables through Resources, to get the source density information
            try {
                return getDrawableFromResourceUri(uri);
            } catch (Resources.NotFoundException ex) {
                throw new FileNotFoundException("Resource does not exist: " + uri);
            }
        } else {
            // Let the ContentResolver handle content and file URIs.
            InputStream stream = mProviderContext.getContentResolver().openInputStream(uri);
            if (stream == null) {
                throw new FileNotFoundException("Failed to open " + uri);
            }
            try {
                return Drawable.createFromStream(stream, null);
            } finally {
                try {
                    stream.close();
                } catch (IOException ex) {
                    Log.e(LOG_TAG, "Error closing icon stream for " + uri, ex);
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
        Log.w(LOG_TAG, "Icon not found: " + uri + ", " + fnfe.getMessage());
        return null;
    }
}

From source file:net.sourceforge.fidocadj.FidoMain.java

/** Inspired from
           /* www. ja va2  s . c  o m*/
   http://richardleggett.co.uk/blog/2013/01/26/
   registering_for_file_types_in_android/
           
   detects if in the data there is a file indication, open it and
   load its contents.
   @return true if something has been loaded, false otherwise
*/
private boolean importData(Uri data) {
    final String scheme = data.getScheme();
    // Check wether there is a file in the data provided.
    if (ContentResolver.SCHEME_FILE.equals(scheme)) {
        try {
            ContentResolver cr = getContentResolver();
            InputStream is = cr.openInputStream(data);
            if (is == null)
                return false;

            // Read the contents of the file.
            StringBuffer buf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String str;
            if (is != null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "\n");
                }
            }
            is.close();
            return true;
        } catch (Exception e) {
            Log.e("fidocadj", "FidoMain.ImportData, Error reading file: " + e.toString());
        }
    }
    return false;
}