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.digitalfeed.pdroidalternative.intenthandler.PackageChangeHandler.java

@Override
public void onReceive(Context context, Intent intent) {
    Log.d("PDroidAlternative", "PackageChangeHandler event received");
    //Get the package name. If this fails, then the intent didn't contain the
    //essential data and should be ignored
    String packageName;/*from  ww w . j  av a2 s  .  com*/
    Uri inputUri = Uri.parse(intent.getDataString());
    if (!inputUri.getScheme().equals("package")) {
        Log.d("PDroidAlternative", "Intent scheme was not 'package'");
        return;
    }
    packageName = inputUri.getSchemeSpecificPart();

    //If a package is being removed, we only want to delete the related
    //info it is not being updated/replaced by a newer version
    if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
        if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
            Log.d("PDroidAlternative", "Triggering application deletion for package:" + packageName);
            DBInterface.getInstance(context).deleteApplicationRecord(packageName);
        }
    } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
        //If the package is just getting updated, then we only need to notify the user
        //if the permissions have changed

        if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
            //TODO: check if the permissions have changed
            Log.d("PDroidAlternative", "PackageChangeHandler: App being replaced: " + packageName);
            Application oldApp = Application.fromDatabase(context, packageName);
            Application newApp = Application.fromPackageName(context, packageName);
            if (havePermissionsChanged(context, oldApp, newApp)) {
                //TODO: Handle permission change
                /*
                 * This is an app for which the permissions have been updated, 
                 * so we need to update the database to include only correct permissions.
                 * Maybe we should have some way of flagging new ones?
                 */
                newApp.setStatusFlags(
                        (newApp.getStatusFlags() | oldApp.getStatusFlags() | Application.STATUS_FLAG_UPDATED)
                                & ~Application.STATUS_FLAG_NEW);
                DBInterface.getInstance(context).updateApplicationRecord(newApp);
                displayNotification(context, NotificationType.update, packageName,
                        DBInterface.getInstance(context).getApplicationLabel(packageName));
            }
        } else {
            /*
             * This is a new app, not an app being replaced. We need to add it to the
             * database, then display a notification for it
             */
            Log.d("PDroidAlternative", "PackageChangeHandler: New app added: " + packageName);
            /*
             * I'm not sure if we really want to be doing all this processing here, but
             * we do need to record a list of new/updated apps to write to the database
             * when the app next starts, or the intent is executed - or we do it now
             */
            //get the application from the system, not from the database
            Application app = Application.fromPackageName(context, packageName);
            app.setStatusFlags(app.getStatusFlags() | Application.STATUS_FLAG_NEW);
            DBInterface.getInstance(context).addApplicationRecord(app);
            Log.d("PDroidAlternative", "PackageChangeHandler: New app record added: " + packageName);
            displayNotification(context, NotificationType.newinstall, packageName, app.getLabel());
            Log.d("PDroidAlternative", "PackageChangeHandler: Notification presented: " + packageName);
        }
    }
}

From source file:org.alfresco.mobile.android.application.extension.scansnap.ScanSnapManagerImpl.java

@Override
public void scan(FragmentActivity activity, Integer presetId) {
    if (hasScanSnapApplication()) {
        AlfrescoNotificationManager notification = AlfrescoNotificationManager.getInstance(appContext);
        String activityId = activity.getApplicationContext().getPackageName();
        try {//from  ww  w. jav a2 s .  c  om
            ScanSnapPreset preset;
            switch (presetId) {
            case DefaultPreset.ID:
                preset = new DefaultPreset(activityId);
                break;
            case DocumentPreset.ID:
                preset = new DocumentPreset(activityId);
                break;
            case PhotoPreset.ID:
                preset = new PhotoPreset(activityId);
                break;
            case BusinessCardPreset.ID:
                preset = new BusinessCardPreset(activityId);
                break;
            default:
                preset = new DefaultPreset(activityId);
                break;
            }

            Uri uri = preset.generateURI();
            Log.d(ScanSnapManagerImpl.TAG, uri.toString());

            // check whether the url format is correct
            if (uri.getScheme() == null) {
                notification.showToast(appContext.getResources().getString(R.string.err_msg_url_parse));
                return;
            }

            Intent in = new Intent();
            in.setData(uri);
            activity.startActivity(in);
        } catch (ActivityNotFoundException e) {
            // specified application can not be found
            notification.showToast(appContext.getResources().getString(R.string.err_msg_launch_failed));
        } catch (NullPointerException e) {
            notification.showToast(appContext.getResources().getString(R.string.err_msg_url_parse));
        }
    }
}

From source file:com.cuddlesoft.norilib.service.ServiceTypeDetectionService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Extract SearchClient.Settings from the received Intent.
    final Uri uri = Uri.parse(intent.getStringExtra(ENDPOINT_URL));
    final Intent broadcastIntent = new Intent(ACTION_DONE);

    if (uri.getHost() == null || uri.getScheme() == null) {
        // The URL supplied is invalid.
        sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_INVALID_URL));
        return;/*  w w w  .j  a v  a  2  s . c  o m*/
    }

    // Create the HTTP client.
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);

    // Iterate over supported URI schemes for given URL.
    for (String uriScheme : (TLS_SUPPORT.contains(uri.getHost()) ? URI_SCHEMES_PREFER_SSL : URI_SCHEMES)) {
        String baseUri = uriScheme + uri.getHost();
        // Iterate over each endpoint path.
        for (Map.Entry<SearchClient.Settings.APIType, String> entry : API_ENDPOINT_PATHS.entrySet()) {
            // Create a HTTP request object.
            final Request request = new Request.Builder().url(baseUri + entry.getValue()).build();

            try {
                // Fetch response.
                final Response response = okHttpClient.newCall(request).execute();
                // Make sure the response code was OK and that the HTTP client wasn't redirected along the way.
                if (response.code() == HttpStatus.SC_OK && response.priorResponse() == null) {
                    // Found an API endpoint.
                    broadcastIntent.putExtra(RESULT_CODE, RESULT_OK);
                    broadcastIntent.putExtra(ENDPOINT_URL, baseUri);
                    broadcastIntent.putExtra(API_TYPE, entry.getKey().ordinal());
                    sendBroadcast(broadcastIntent);
                    return;
                }
            } catch (IOException e) {
                // Network error. Notify the listeners and return.
                sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NETWORK));
                return;
            }
        }
    }

    // End of the loop was reached without finding an API endpoint. Send error code to the BroadcastReceiver.
    sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NO_API));
}

From source file:com.android.dialer.lookup.yellowpages.YellowPagesReverseLookup.java

/**
 * Lookup image/*ww  w .  java 2 s.  c  o m*/
 *
 * @param context The application context
 * @param uri The image URI
 */
public Bitmap lookupImage(Context context, Uri uri) {
    if (uri == null) {
        throw new NullPointerException("URI is null");
    }

    Log.e(TAG, "Fetching " + uri);

    String scheme = uri.getScheme();

    if (scheme.startsWith("http")) {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri.toString());

        try {
            HttpResponse response = client.execute(request);

            int responseCode = response.getStatusLine().getStatusCode();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            byte[] responseBytes = out.toByteArray();

            if (responseCode == HttpStatus.SC_OK) {
                Bitmap bmp = BitmapFactory.decodeByteArray(responseBytes, 0, responseBytes.length);
                return bmp;
            }
        } catch (IOException e) {
            Log.e(TAG, "Failed to retrieve image", e);
        }
    } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
        try {
            ContentResolver cr = context.getContentResolver();
            Bitmap bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
            return bmp;
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Failed to retrieve image", e);
        }
    }

    return null;
}

From source file:at.bitfire.davdroid.ui.setup.LoginCredentialsFragment.java

protected LoginCredentials validateLoginData() {
    if (radioUseEmail.isChecked()) {
        URI uri = null;//from  w  w w  . j a v  a2 s  .  com
        boolean valid = true;

        String email = editEmailAddress.getText().toString();
        if (!email.matches(".+@.+")) {
            editEmailAddress.setError(getString(R.string.login_email_address_error));
            valid = false;
        } else
            try {
                uri = new URI("mailto", email, null);
            } catch (URISyntaxException e) {
                editEmailAddress.setError(e.getLocalizedMessage());
                valid = false;
            }

        String password = editEmailPassword.getText().toString();
        if (password.isEmpty()) {
            editEmailPassword.setError(getString(R.string.login_password_required));
            valid = false;
        }

        return valid ? new LoginCredentials(uri, email, password) : null;

    } else if (radioUseURL.isChecked()) {
        URI uri = null;
        boolean valid = true;

        Uri baseUrl = Uri.parse(editBaseURL.getText().toString());
        String scheme = baseUrl.getScheme();
        if ("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)) {
            String host = baseUrl.getHost();
            if (StringUtils.isEmpty(host)) {
                editBaseURL.setError(getString(R.string.login_url_host_name_required));
                valid = false;
            } else
                try {
                    host = IDN.toASCII(host);
                } catch (IllegalArgumentException e) {
                    Constants.log.log(Level.WARNING, "Host name not conforming to RFC 3490", e);
                }

            String path = baseUrl.getEncodedPath();
            int port = baseUrl.getPort();
            try {
                uri = new URI(baseUrl.getScheme(), null, host, port, path, null, null);
            } catch (URISyntaxException e) {
                editBaseURL.setError(e.getLocalizedMessage());
                valid = false;
            }
        } else {
            editBaseURL.setError(getString(R.string.login_url_must_be_http_or_https));
            valid = false;
        }

        String userName = editUserName.getText().toString();
        if (userName.isEmpty()) {
            editUserName.setError(getString(R.string.login_user_name_required));
            valid = false;
        }

        String password = editUrlPassword.getText().toString();
        if (password.isEmpty()) {
            editUrlPassword.setError(getString(R.string.login_password_required));
            valid = false;
        }

        return valid ? new LoginCredentials(uri, userName, password) : null;
    }

    return null;
}

From source file:edu.mit.mobile.android.demomode.Preferences.java

private void fromCfgString(String cfg) {
    final Uri cfgUri = Uri.parse(cfg);
    if ("data".equals(cfgUri.getScheme())) {
        final String[] cfgParts = cfgUri.getEncodedSchemeSpecificPart().split(",", 2);
        if (CFG_MIME_TYPE.equals(cfgParts[0])) {
            final Editor ed = mPrefs.edit();
            final ArrayList<ContentProviderOperation> cpos = new ArrayList<ContentProviderOperation>();

            // first erase everything
            cpos.add(ContentProviderOperation.newDelete(LauncherItem.CONTENT_URI).build());

            try {
                final StringEntity entity = new StringEntity(cfgParts[1]);
                entity.setContentType("application/x-www-form-urlencoded");
                final List<NameValuePair> nvp = URLEncodedUtils.parse(entity);
                for (final NameValuePair pair : nvp) {
                    final String name = pair.getName();
                    Log.d(TAG, "parsed pair: " + pair);
                    if (CFG_K_SECRETKEY.equals(name)) {
                        ed.putString(KEY_PASSWORD, pair.getValue());

                    } else if (CFG_K_APPS.equals(name)) {
                        final String[] app = pair.getValue().split(CFG_PKG_SEP, 2);
                        final ContentProviderOperation cpo = ContentProviderOperation
                                .newInsert(LauncherItem.CONTENT_URI)
                                .withValue(LauncherItem.PACKAGE_NAME, app[0])
                                .withValue(LauncherItem.ACTIVITY_NAME, app[1]).build();
                        cpos.add(cpo);/*from   ww w. j a  v  a2s  . co  m*/
                        Log.d(TAG, "adding " + cpo);
                    }
                }

                ed.commit();
                getContentResolver().applyBatch(HomescreenProvider.AUTHORITY, cpos);
            } catch (final UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final RemoteException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            } catch (final OperationApplicationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            Log.e(TAG, "unknown MIME type for data URI: " + cfgParts[0]);
        }

    } else {
        Log.e(TAG, "not a data URI");
    }
}

From source file:com.commonsware.android.tte.DocumentStorageService.java

private void save(Uri document, String text, boolean isClosing) {
    boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme());

    try {/*from  w  w w. j  a va2s .  c  o m*/
        OutputStream os = getContentResolver().openOutputStream(document, "w");
        OutputStreamWriter osw = new OutputStreamWriter(os);

        try {
            osw.write(text);
            osw.flush();

            if (isClosing && isContent) {
                int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

                getContentResolver().releasePersistableUriPermission(document, perms);
            }

            EventBus.getDefault().post(new DocumentSavedEvent(document));
        } finally {
            osw.close();
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception saving " + document.toString(), e);
        EventBus.getDefault().post(new DocumentSaveErrorEvent(document, e));
    }
}

From source file:com.remobile.file.AssetFilesystem.java

@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
    if (!"file".equals(inputURL.getScheme())) {
        return null;
    }//from  ww  w. j ava 2  s  . com
    File f = new File(inputURL.getPath());
    // Removes and duplicate /s (e.g. file:///a//b/c)
    Uri resolvedUri = Uri.fromFile(f);
    String rootUriNoTrailingSlash = rootUri.getEncodedPath();
    rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
    if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
        return null;
    }
    String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
    // Strip leading slash
    if (!subPath.isEmpty()) {
        subPath = subPath.substring(1);
    }
    Uri.Builder b = new Uri.Builder().scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL).authority("localhost")
            .path(name);
    if (!subPath.isEmpty()) {
        b.appendEncodedPath(subPath);
    }
    if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
        // Add trailing / for directories.
        b.appendEncodedPath("");
    }
    return LocalFilesystemURL.parse(b.build());
}

From source file:com.commonsware.android.tte.MainActivity.java

private void openEditor(Uri document) {
    if (ContentResolver.SCHEME_CONTENT.equals(document.getScheme()) || canWriteFiles()) {
        int position = adapter.getPositionForDocument(document);

        if (position == -1) {
            adapter.addDocument(document);
            pager.setCurrentItem(adapter.getCount() - 1);

            if (!editHistory.addOpenEditor(document)) {
                Toast.makeText(this, R.string.msg_save_history, Toast.LENGTH_LONG).show();
            }/*from w  ww  .  j  a va2  s  .  co  m*/
        } else {
            pager.setCurrentItem(position);
        }
    } else if (ContentResolver.SCHEME_FILE.equals(document.getScheme())) {
        pendingFiles.add(document);
        ActivityCompat.requestPermissions(this, PERMS_FILE, REQUEST_PERMS_FILE);
    }
}

From source file:com.lloydtorres.stately.helpers.SparkleHelper.java

/**
 * Finds all raw URL links and URL tags and linkifies them properly in a nice format.
 * @param c App context.// w  ww  . ja va2s.c  o  m
 * @param content Target string.
 * @return Parsed results.
 */
public static String regexGenericUrlFormat(Context c, String content) {
    String holder = content;

    Map<String, String> replaceBasic = new HashMap<String, String>();
    Matcher m0 = BBCODE_URL.matcher(holder);
    while (m0.find()) {
        String template = "<a href=\"%s\">%s</a>";
        Uri link = Uri.parse(m0.group(1)).normalizeScheme();
        if (link.getScheme() == null) {
            template = "<a href=\"http://%s\">%s</a>";
        }
        String replaceText = String.format(Locale.US, template, link.toString(), m0.group(2));
        replaceBasic.put(m0.group(), replaceText);
    }
    Set<Map.Entry<String, String>> setBasic = replaceBasic.entrySet();
    for (Map.Entry<String, String> e : setBasic) {
        holder = holder.replace(e.getKey(), e.getValue());
    }

    Map<String, String> replaceRaw = new HashMap<String, String>();

    Matcher m1 = RAW_HTTP_LINK.matcher(holder);
    while (m1.find()) {
        Uri link = Uri.parse(m1.group(1)).normalizeScheme();
        String replaceText = String.format(Locale.US, c.getString(R.string.clicky_link_http), link.toString(),
                link.getHost());
        replaceRaw.put(m1.group(), replaceText);
    }

    Matcher m2 = RAW_WWW_LINK.matcher(holder);
    while (m2.find()) {
        Uri link = Uri.parse("http://" + m2.group(1)).normalizeScheme();
        String replaceText = String.format(Locale.US, c.getString(R.string.clicky_link_http), link.toString(),
                link.getHost());
        replaceRaw.put(m2.group(), replaceText);
    }

    Set<Map.Entry<String, String>> set = replaceRaw.entrySet();
    for (Map.Entry<String, String> e : set) {
        holder = holder.replaceAll(
                "(?<=^|\\s|<br \\/>|<br>|<b>|<i>|<u>)\\Q" + e.getKey() + "\\E(?=$|[\\s\\[\\<])", e.getValue());
    }

    return holder;
}