Example usage for android.net Uri getHost

List of usage examples for android.net Uri getHost

Introduction

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

Prototype

@Nullable
public abstract String getHost();

Source Link

Document

Gets the encoded host from the authority for this URI.

Usage

From source file:org.fdroid.fdroid.net.DownloaderService.java

/**
 * This method is invoked on the worker thread with a request to process.
 * Only one Intent is processed at a time, but the processing happens on a
 * worker thread that runs independently from other application logic.
 * So, if this code takes a long time, it will hold up other requests to
 * the same DownloaderService, but it will not hold up anything else.
 * When all requests have been handled, the DownloaderService stops itself,
 * so you should not ever call {@link #stopSelf}.
 * <p/>//from   ww  w  .  j a v a  2 s  .  c om
 * Downloads are put into subdirectories based on hostname/port of each repo
 * to prevent files with the same names from conflicting.  Each repo enforces
 * unique APK file names on the server side.
 *
 * @param intent The {@link Intent} passed via {@link
 *               android.content.Context#startService(Intent)}.
 */
protected void handleIntent(Intent intent) {
    final Uri uri = intent.getData();
    File downloadDir = new File(Utils.getApkCacheDir(this), uri.getHost() + "-" + uri.getPort());
    downloadDir.mkdirs();
    final SanitizedFile localFile = new SanitizedFile(downloadDir, uri.getLastPathSegment());
    final String packageName = getPackageNameFromIntent(intent);
    sendBroadcast(uri, Downloader.ACTION_STARTED, localFile);

    if (Preferences.get().isUpdateNotificationEnabled()) {
        Notification notification = createNotification(intent.getDataString(), getPackageNameFromIntent(intent))
                .build();
        startForeground(NOTIFY_DOWNLOADING, notification);
    }

    try {
        downloader = DownloaderFactory.create(this, uri, localFile);
        downloader.setListener(new Downloader.DownloaderProgressListener() {
            @Override
            public void sendProgress(URL sourceUrl, int bytesRead, int totalBytes) {
                if (isActive(uri.toString())) {
                    Intent intent = new Intent(Downloader.ACTION_PROGRESS);
                    intent.setData(uri);
                    intent.putExtra(Downloader.EXTRA_BYTES_READ, bytesRead);
                    intent.putExtra(Downloader.EXTRA_TOTAL_BYTES, totalBytes);
                    localBroadcastManager.sendBroadcast(intent);

                    if (Preferences.get().isUpdateNotificationEnabled()) {
                        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        Notification notification = createNotification(uri.toString(), packageName)
                                .setProgress(totalBytes, bytesRead, false).build();
                        nm.notify(NOTIFY_DOWNLOADING, notification);
                    }
                }
            }
        });
        downloader.download();
        sendBroadcast(uri, Downloader.ACTION_COMPLETE, localFile);
        DownloadCompleteService.notify(this, packageName, intent.getDataString());
    } catch (InterruptedException e) {
        sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile);
    } catch (IOException e) {
        e.printStackTrace();
        sendBroadcast(uri, Downloader.ACTION_INTERRUPTED, localFile, e.getLocalizedMessage());
    } finally {
        if (downloader != null) {
            downloader.close();
        }
        // May have already been removed in response to a cancel intent, but that wont cause
        // problems if we ask to remove it again.
        QUEUE_WHATS.remove(uri.toString());
        stopForeground(true);
    }
    downloader = null;
}

From source file:com.timrae.rikaidroid.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebClient = new WebViewClient() {
        @Override/*from w ww  .j ava2 s .  c om*/
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);
            if (uri.getScheme().equals("lookup")) {
                String query = uri.getHost();
                Intent i = new Intent(AEDICT_INTENT);
                i.putExtra("kanjis", query);
                i.putExtra("showEntryDetailOnSingleResult", true);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                view.reload();
                return true;
            }

            else {
                view.loadUrl(url);
            }
            return true;
        }
    };
    mWebView.setWebViewClient(mWebClient);
    mEditText = (EditText) findViewById(R.id.search_src_text);
    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    if (mProgressBar != null) {
        mProgressBar.setVisibility(View.VISIBLE);
    }

}

From source file:ca.rmen.android.poetassistant.main.MainActivity.java

private void handleDeepLink(Uri uri) {
    Log.d(TAG, "handleDeepLink() called with: " + "uri = [" + uri + "]");
    if (uri == null)
        return;//from   w ww.  java  2  s  . c o m
    String word = uri.getLastPathSegment();
    if (Constants.DEEP_LINK_QUERY.equals(uri.getHost())) {
        mSearch.search(word);
        mBinding.viewPager.setCurrentItem(mPagerAdapter.getPositionForTab(Tab.DICTIONARY));
    } else {
        Tab tab = Tab.parse(uri.getHost());
        if (tab != null)
            mSearch.search(word, tab);
    }
}

From source file:ir.keloud.android.lib.common.KeloudSamlSsoCredentials.java

@Override
public void applyTo(KeloudClient client) {
    client.getParams().setAuthenticationPreemptive(false);
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setFollowRedirects(false);/*from   w ww .j  a v a2 s  .  c o m*/

    Uri serverUri = client.getBaseUri();

    String[] cookies = mSessionCookie.split(";");
    if (cookies.length > 0) {
        Cookie cookie = null;
        for (int i = 0; i < cookies.length; i++) {
            int equalPos = cookies[i].indexOf('=');
            if (equalPos >= 0) {
                cookie = new Cookie();
                cookie.setName(cookies[i].substring(0, equalPos));
                cookie.setValue(cookies[i].substring(equalPos + 1));
                cookie.setDomain(serverUri.getHost()); // VERY IMPORTANT 
                cookie.setPath(serverUri.getPath()); // VERY IMPORTANT
                client.getState().addCookie(cookie);
            }
        }
    }
}

From source file:com.cerema.cloud2.lib.common.OwnCloudSamlSsoCredentials.java

@Override
public void applyTo(OwnCloudClient client) {
    client.getParams().setAuthenticationPreemptive(false);
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setFollowRedirects(false);//from w ww  .  j av  a 2 s. c  o m

    Uri serverUri = client.getBaseUri();

    String[] cookies = mSessionCookie.split(";");
    if (cookies.length > 0) {
        Cookie cookie = null;
        for (int i = 0; i < cookies.length; i++) {
            int equalPos = cookies[i].indexOf('=');
            if (equalPos >= 0) {
                cookie = new Cookie();
                cookie.setName(cookies[i].substring(0, equalPos));
                cookie.setValue(cookies[i].substring(equalPos + 1));
                cookie.setDomain(serverUri.getHost()); // VERY IMPORTANT 
                cookie.setPath(serverUri.getPath()); // VERY IMPORTANT
                client.getState().addCookie(cookie);
            }
        }
    }
}

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Display dialog to the user for the browser bookmarks. Allow the user to add a
 * browser bookmark to an existing row or a new row.
 * // w  ww .  j a va2 s . com
 * @param context
 */
public static void displayAddBrowserBookmark(final Launcher context) {
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.add_browser_bookmarks_list);

    final EditText nameEditText = (EditText) dialog.findViewById(R.id.rowName);
    final RadioButton currentRadioButton = (RadioButton) dialog.findViewById(R.id.currentRadio);
    currentRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // hide the row name edit field if the current row radio button
            // is selected
            nameEditText.setVisibility(View.GONE);
        }

    });
    final RadioButton newRadioButton = (RadioButton) dialog.findViewById(R.id.newRadio);
    newRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // show the row name edit field if the new radio button is
            // selected
            nameEditText.setVisibility(View.VISIBLE);
            nameEditText.requestFocus();
        }

    });

    ListView listView = (ListView) dialog.findViewById(R.id.list);
    final ArrayList<BookmarkInfo> bookmarks = loadBookmarks(context);
    Collections.sort(bookmarks, new Comparator<BookmarkInfo>() {

        @Override
        public int compare(BookmarkInfo lhs, BookmarkInfo rhs) {
            return lhs.getTitle().toLowerCase().compareTo(rhs.getTitle().toLowerCase());
        }

    });
    listView.setAdapter(new BookmarkAdapter(context, bookmarks));
    listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            // run in thread since network logic needed to get bookmark icon
            new Thread(new Runnable() {
                public void run() {
                    // if the new row radio button is selected, the user must enter
                    // a name for the new row
                    String name = nameEditText.getText().toString().trim();
                    if (newRadioButton.isChecked() && name.length() == 0) {
                        nameEditText.requestFocus();
                        displayAlert(context, context.getString(R.string.dialog_new_row_name_alert));
                        return;
                    }
                    boolean currentRow = !newRadioButton.isChecked();
                    try {
                        BookmarkInfo bookmark = (BookmarkInfo) parent.getAdapter().getItem(position);
                        int rowId = 0;
                        int rowPosition = 0;
                        if (currentRow) {
                            rowId = context.getCurrentGalleryId();
                            ArrayList<ItemInfo> items = ItemsTable.getItems(context, rowId);
                            rowPosition = items.size(); // in last
                            // position
                            // for selected
                            // row
                        } else {
                            rowId = (int) RowsTable.insertRow(context, name, 0, RowInfo.FAVORITE_TYPE);
                            rowPosition = 0;
                        }
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(bookmark.getUrl()));

                        Uri uri = Uri.parse(bookmark.getUrl());
                        Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost());
                        String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost());
                        Log.d(LOG_TAG, "icon1=" + icon);
                        if (icon == null) {
                            // try base host address
                            int count = StringUtils.countMatches(uri.getHost(), ".");
                            if (count > 1) {
                                int index = uri.getHost().indexOf('.');
                                String baseHost = uri.getHost().substring(index + 1);
                                icon = Utils.getWebSiteIcon(context, "http://" + baseHost);
                                Log.d(LOG_TAG, "icon2=" + icon);
                            }
                        }

                        ItemsTable.insertItem(context, rowId, rowPosition, bookmark.getTitle(), intent, icon,
                                DatabaseHelper.SHORTCUT_TYPE);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "displayAddBrowserBookmark", e);
                    }

                    // need to do this on UI thread
                    context.getHandler().post(new Runnable() {
                        public void run() {
                            context.showCover(false);
                            dialog.dismiss();
                            context.reloadAllGalleries();
                        }
                    });

                    if (currentRow) {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK);
                    } else {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK_WITH_ROW);
                    }

                }
            }).start();
        }
    });
    listView.setDrawingCacheEnabled(true);
    listView.setOnKeyListener(onKeyListener);
    dialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            context.showCover(false);
        }

    });
    context.showCover(true);
    dialog.show();
    Analytics.logEvent(Analytics.DIALOG_ADD_BROWSER_BOOKMARK);
}

From source file:com.takondi.tartt.ARActivity.java

private void processQr(String qrContent) {
    Uri qrUri = Uri.parse(qrContent);
    if (QR_TARTT_SCHEME.equals(qrUri.getScheme()) && QR_CHANNEL_HOST.equals(qrUri.getHost())
            && qrUri.getQueryParameter(Channel.CHANNEL_KEY) != null) {
        //we now might also be receiving a scanned qr/barcode out of an active world, so let's make sure to deactivate the world's AR
        loadDefaultWorld();//from  www .ja v  a  2 s  .c  o m

        mGuiHelper.changeGuiState(GUI_STATE.LOADING);
        TarttRequestOptions newConfig = Tartt
                .getInitialConfigForChannel(qrUri.getQueryParameter(Channel.CHANNEL_KEY));
        try {
            if (qrUri.getQueryParameter(Channel.STATE) != null) {
                newConfig.setState(TarttRequestOptions.State
                        .getStateForValue(Integer.valueOf(qrUri.getQueryParameter(Channel.STATE))));
            }
            if (qrUri.getQueryParameter(Channel.TARGET_TYPE) != null) {
                newConfig.setTargetType(
                        TarttRequestOptions.TargetType.valueOf(qrUri.getQueryParameter(Channel.TARGET_TYPE)));
            }
            if (qrUri.getQueryParameter(Channel.ENV_TYPE) != null) {
                newConfig.setEnvType(
                        TarttRequestOptions.EnvironmentType.valueOf(qrUri.getQueryParameter(Channel.ENV_TYPE)));
            }
            if (qrUri.getQueryParameter(Channel.TARGET_API) != null) {
                newConfig.setTargetApi(Integer.valueOf(qrUri.getQueryParameter(Channel.TARGET_API)));
            }
            if (qrUri.getQueryParameter(Channel.LANGUAGE) != null) {
                newConfig.setLanguage(qrUri.getQueryParameter(Channel.LANGUAGE));
            }
        } catch (NumberFormatException eNFE) {
            Log.e(TAG, "QR-Code contained invalid value for parameter (requires a number)");
        } catch (IllegalArgumentException eIAE) {
            Log.e(TAG, "QR-Code contained invalid value for a parameter (not in valid range)");
        }
        mChannelManager.fetchFilesForChannelWithConfig(newConfig, this);
    } else {
        mQrPlugin.activate();
    }
}

From source file:eu.e43.impeller.activity.MainActivity.java

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    m_pendingIntent = false;//w  w  w  . j  ava2 s.  c  o  m
    Log.i(TAG, "New intent " + intent);

    if (intent.hasExtra(Constants.EXTRA_ACCOUNT)) {
        haveGotAccount((Account) intent.getParcelableExtra(Constants.EXTRA_ACCOUNT));
    }

    if (m_account == null) {
        setIntent(intent);
        m_pendingIntent = true;
        return;
    }

    String action = intent.getAction();
    if (Intent.ACTION_VIEW.equals(action)) {
        Uri uri = intent.getData();
        if (uri == null)
            return;

        Uri id = null;
        if (uri.getScheme().equals("content") && uri.getHost().equals("eu.e43.impeller.content")) {
            id = Uri.parse(uri.getLastPathSegment());
        } else {
            id = uri;
        }

        setIntent(intent);
        showObjectInMode(Mode.OBJECT, id);
    } else if (Constants.ACTION_SHOW_FEED.equals(action)) {
        showFeed((Constants.FeedID) intent.getSerializableExtra(Constants.EXTRA_FEED_ID));
    } else {
        Log.d(TAG, "Unknown new intent " + intent);
    }
}

From source file:com.vuze.android.remote.activity.IntentHandler.java

private boolean handleIntent(Intent intent, Bundle savedInstanceState) {
    boolean forceProfileListOpen = (intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_TOP) > 0;

    if (AndroidUtils.DEBUG) {
        Log.d(TAG, "ForceOpen? " + forceProfileListOpen);
        Log.d(TAG, "IntentHandler intent = " + intent);
    }/*w  w  w .  j  av a  2 s .  c  o  m*/

    appPreferences = VuzeRemoteApp.getAppPreferences();

    Uri data = intent.getData();
    if (data != null) {
        try {
            // check for vuze://remote//*
            String scheme = data.getScheme();
            String host = data.getHost();
            String path = data.getPath();
            if ("vuze".equals(scheme) && "remote".equals(host) && path != null && path.length() > 1) {
                String ac = path.substring(1);
                if (AndroidUtils.DEBUG) {
                    Log.d(TAG, "got ac '" + ac + "' from " + data);
                }

                intent.setData(null);
                if (ac.equals("cmd=advlogin")) {
                    DialogFragmentGenericRemoteProfile dlg = new DialogFragmentGenericRemoteProfile();
                    AndroidUtils.showDialog(dlg, getSupportFragmentManager(), "GenericRemoteProfile");
                    forceProfileListOpen = true;
                } else if (ac.length() < 100) {
                    RemoteProfile remoteProfile = new RemoteProfile("vuze", ac);
                    new RemoteUtils(this).openRemote(remoteProfile, true);
                    finish();
                    return true;
                }
            }

            // check for http[s]://remote.vuze.com/ac=*
            if (host != null && host.equals("remote.vuze.com") && data.getQueryParameter("ac") != null) {
                String ac = data.getQueryParameter("ac");
                if (AndroidUtils.DEBUG) {
                    Log.d(TAG, "got ac '" + ac + "' from " + data);
                }
                intent.setData(null);
                if (ac.length() < 100) {
                    RemoteProfile remoteProfile = new RemoteProfile("vuze", ac);
                    new RemoteUtils(this).openRemote(remoteProfile, true);
                    finish();
                    return true;
                }
            }
        } catch (Exception e) {
            if (AndroidUtils.DEBUG) {
                e.printStackTrace();
            }
        }
    }

    if (!forceProfileListOpen) {
        int numRemotes = getRemotesWithLocal().length;
        if (numRemotes == 0) {
            // New User: Send them to Login (Account Creation)
            Intent myIntent = new Intent(Intent.ACTION_VIEW, null, this, LoginActivity.class);
            myIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);

            startActivity(myIntent);
            finish();
            return true;
        } else if (numRemotes == 1 || intent.getData() == null) {
            try {
                RemoteProfile remoteProfile = appPreferences.getLastUsedRemote();
                if (remoteProfile != null) {
                    if (savedInstanceState == null) {
                        new RemoteUtils(this).openRemote(remoteProfile, true);
                        finish();
                        return true;
                    }
                } else {
                    Log.d(TAG, "Has Remotes, but no last remote");
                }
            } catch (Throwable t) {
                if (AndroidUtils.DEBUG) {
                    Log.e(TAG, "onCreate", t);
                }
                VuzeEasyTracker.getInstance(this).logError(t);
            }
        }
    }
    return false;
}

From source file:com.activiti.android.app.fragments.integration.alfresco.AlfrescoIntegrationFragment.java

private void updateUI() {
    hide(R.id.validation_panel);//  w  w  w  . j  a v a  2  s .  c o m

    // The idea is to get Integration Information and compare them to
    // alfresco account.
    if (checkActivity()) {
        return;
    }

    // Retrieve information from activiti Account
    if (getArguments() != null) {
        accountId = BundleUtils.getLong(getArguments(), ARGUMENT_ACCOUNT_ID);
        activitiAccount = ActivitiAccountManager.getInstance(getActivity()).getByAccountId(accountId);
    }

    // We have alfresco account integration
    // Is Alfresco APP Present ?
    // Is Alfresco Version recent ?
    PackageInfo info = getAlfrescoInfo(getActivity());
    boolean outdated = (info != null && info.versionCode < 40);
    if (info == null || outdated) {
        // Alfresco APP is not present...
        // We request the installation from the play store
        titleTv.setText(
                getString(outdated ? R.string.settings_alfresco_update : R.string.settings_alfresco_install));

        summaryTv.setText(Html.fromHtml(getString(outdated ? R.string.settings_alfresco_update_summary
                : R.string.settings_alfresco_install_summary)));

        actionButton.setText(getString(outdated ? R.string.settings_alfresco_update_action
                : R.string.settings_alfresco_install_action));
        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPlayStore();
            }
        });

        hide(R.id.validation_panel);

        return;
    }

    // Alfresco APP is present
    actionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectedAccount = null;
            launchAccountSelect();
        }
    });

    // Retrieve Alfresco Account
    Account[] accounts = AccountManager.get(getActivity())
            .getAccountsByType(AlfrescoIntegrator.ALFRESCO_ACCOUNT_TYPE);
    if (accounts.length == 0 && selectedAccount == null) {
        // Need to create an alfresco account!
        titleTv.setText(getString(R.string.settings_alfresco_not_found));
        summaryTv.setText(Html.fromHtml(getString(R.string.settings_alfresco_not_found_summary)));
        actionButton.setText(getString(R.string.settings_alfresco_not_found_action));
        /*
         * actionButton.setOnClickListener(new View.OnClickListener() {
         * @Override public void onClick(View v) { selectedAccount = null;
         * Intent i = AlfrescoIntegrator.createAccount(getActivity(),
         * selectedIntegration.getRepositoryUrl(),
         * activitiAccount.getUsername()); startActivityForResult(i, 10); }
         * });
         */

        return;
    }

    // An activitiAccount match if username == username
    for (int i = 0; i < accounts.length; i++) {
        String username = AccountManager.get(getActivity()).getUserData(accounts[i],
                BuildConfig.ALFRESCO_ACCOUNT_ID.concat(".username"));

        if (activitiAccount.getUsername().equals(username)) {
            // Lets compare hostname
            String alfUrl = AccountManager.get(getActivity()).getUserData(accounts[i],
                    BuildConfig.ALFRESCO_ACCOUNT_ID.concat(".url"));
            Uri alfUri = Uri.parse(alfUrl);
            Uri activitiUri = Uri.parse(selectedIntegration.getRepositoryUrl());

            if (alfUri != null && activitiUri != null && alfUri.getHost().equals(activitiUri.getHost())) {
                // We found one !
                selectedAccount = accounts[i];
                break;
            }
        }
    }

    // Have found ?
    if (selectedAccount != null) {
        alfrescoId = AccountManager.get(getActivity()).getUserData(selectedAccount,
                BuildConfig.ALFRESCO_ACCOUNT_ID.concat(".id"));
        alfrescoUsername = AccountManager.get(getActivity()).getUserData(selectedAccount,
                BuildConfig.ALFRESCO_ACCOUNT_ID.concat(".username"));
        alfrescoAccountName = AccountManager.get(getActivity()).getUserData(selectedAccount,
                BuildConfig.ALFRESCO_ACCOUNT_ID.concat(".name"));

        titleTv.setText(getString(R.string.settings_alfresco_account_found));

        summaryTv.setText(
                Html.fromHtml(String.format(getString(R.string.settings_alfresco_account_found_summary),
                        alfrescoAccountName, alfrescoUsername)));

        actionButton.setText(getString(R.string.settings_alfresco_account_found_action));

        show(R.id.validation_panel);
        Button validate = UIUtils.initValidation(getRootView(), R.string.general_action_confirm);
        validate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveIntegration();
            }
        });
        Button cancel = UIUtils.initCancel(getRootView(), R.string.general_action_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
    } else {
        titleTv.setText(getString(R.string.settings_alfresco_account_found));
        summaryTv.setText(Html.fromHtml(getString(R.string.settings_alfresco_not_found_summary)));
        actionButton.setText(getString(R.string.settings_alfresco_not_found_action));

        hide(R.id.validation_panel);
    }
}