Example usage for android.net Uri getFragment

List of usage examples for android.net Uri getFragment

Introduction

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

Prototype

@Nullable
public abstract String getFragment();

Source Link

Document

Gets the decoded fragment part of this URI, everything after the '#'.

Usage

From source file:io.ionic.links.IonicDeeplink.java

public void handleIntent(Intent intent) {
    final String intentString = intent.getDataString();

    // read intent
    String action = intent.getAction();
    Uri url = intent.getData();
    JSONObject bundleData = this._bundleToJson(intent.getExtras());
    Log.d(TAG, "Got a new intent: " + intentString + " " + intent.getScheme() + " " + action + " " + url);

    // if app was not launched by the url - ignore
    if (!Intent.ACTION_VIEW.equals(action) || url == null) {
        return;/*from  w w  w  .  j a  va2s .c o  m*/
    }

    // store message and try to consume it
    try {
        lastEvent = new JSONObject();
        lastEvent.put("url", url.toString());
        lastEvent.put("path", url.getPath());
        lastEvent.put("queryString", url.getQuery());
        lastEvent.put("scheme", url.getScheme());
        lastEvent.put("host", url.getHost());
        lastEvent.put("fragment", url.getFragment());
        lastEvent.put("extra", bundleData);
        consumeEvents();
    } catch (JSONException ex) {
        Log.e(TAG, "Unable to process URL scheme deeplink", ex);
    }
}

From source file:com.appbase.androidquery.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;

    return result;
}

From source file:com.microsoft.services.msa.AuthorizationRequest.java

/**
 * Called when the end uri is loaded.//from   ww w .  ja  v  a 2s . co  m
 *
 * This method will read the uri's query parameters and fragment, and respond with the
 * appropriate action.
 *
 * @param endUri that was loaded
 */
private void onEndUri(Uri endUri) {
    // If we are on an end uri, the response could either be in
    // the fragment or the query parameters. The response could
    // either be successful or it could contain an error.
    // Check all situations and call the listener's appropriate callback.
    // Callback the listener on the UI/main thread. We could call it right away since
    // we are on the UI/main thread, but it is probably better that we finish up with
    // the WebView code before we callback on the listener.
    boolean hasFragment = endUri.getFragment() != null;
    boolean hasQueryParameters = endUri.getQuery() != null;
    boolean invalidUri = !hasFragment && !hasQueryParameters;
    boolean isHierarchical = endUri.isHierarchical();

    // check for an invalid uri, and leave early
    if (invalidUri) {
        this.onInvalidUri();
        return;
    }

    if (hasFragment) {
        Map<String, String> fragmentParameters = AuthorizationRequest.getFragmentParametersMap(endUri);

        boolean isSuccessfulResponse = fragmentParameters.containsKey(OAuth.ACCESS_TOKEN)
                && fragmentParameters.containsKey(OAuth.TOKEN_TYPE);
        if (isSuccessfulResponse) {

            //                SharedPreferences preferences = activity.getSharedPreferences("csPrivateSpace", Context.MODE_PRIVATE);
            //                SharedPreferences.Editor editor = preferences.edit();
            //                editor.putString("funUserID", fragmentParameters.get("user_id"));
            //                editor.apply();

            this.onAccessTokenResponse(fragmentParameters);
            return;
        }

        String error = fragmentParameters.get(OAuth.ERROR);
        if (error != null) {
            String errorDescription = fragmentParameters.get(OAuth.ERROR_DESCRIPTION);
            String errorUri = fragmentParameters.get(OAuth.ERROR_URI);
            this.onError(error, errorDescription, errorUri);
            return;
        }
    }

    if (hasQueryParameters && isHierarchical) {
        String code = endUri.getQueryParameter(OAuth.CODE);
        if (code != null) {
            this.onAuthorizationResponse(code);
            return;
        }

        String error = endUri.getQueryParameter(OAuth.ERROR);
        if (error != null) {
            String errorDescription = endUri.getQueryParameter(OAuth.ERROR_DESCRIPTION);
            String errorUri = endUri.getQueryParameter(OAuth.ERROR_URI);
            this.onError(error, errorDescription, errorUri);
            return;
        }
    }

    if (hasQueryParameters && !isHierarchical) {
        String[] pairs = endUri.getQuery().split("&|=");
        for (int i = 0; i < pairs.length; i = +2) {
            if (pairs[i].equals(OAuth.CODE)) {
                this.onAuthorizationResponse(pairs[i + 1]);
                return;
            }
        }
    }

    // if the code reaches this point, the uri was invalid
    // because it did not contain either a successful response
    // or an error in either the queryParameter or the fragment
    this.onInvalidUri();
}

From source file:org.geometerplus.android.fbreader.FBReader.java

@Override
protected void onNewIntent(final Intent intent) {
    final String action = intent.getAction();
    final Uri data = intent.getData();

    if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
        super.onNewIntent(intent);
    } else if (Intent.ACTION_VIEW.equals(action) && data != null
            && "fbreader-action".equals(data.getScheme())) {
        myFBReaderApp.runAction(data.getEncodedSchemeSpecificPart(), data.getFragment());
    } else if (Intent.ACTION_VIEW.equals(action) || FBReaderIntents.Action.VIEW.equals(action)) {
        myOpenBookIntent = intent;//from  w  ww. j a  va2 s  . c  om
        if (myFBReaderApp.Model == null && myFBReaderApp.ExternalBook != null) {
            final ExternalFormatPlugin plugin = (ExternalFormatPlugin) myFBReaderApp.ExternalBook
                    .getPluginOrNull();
            try {
                startActivity(PluginUtil.createIntent(plugin, PluginUtil.ACTION_KILL));
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
            }
        }
    } else if (FBReaderIntents.Action.PLUGIN.equals(action)) {
        new RunPluginAction(this, myFBReaderApp, data).run();
    } else if (Intent.ACTION_SEARCH.equals(action)) {
        final String pattern = intent.getStringExtra(SearchManager.QUERY);
        final Runnable runnable = new Runnable() {
            public void run() {
                final TextSearchPopup popup = (TextSearchPopup) myFBReaderApp.getPopupById(TextSearchPopup.ID);
                popup.initPosition();
                myFBReaderApp.MiscOptions.TextSearchPattern.setValue(pattern);
                if (myFBReaderApp.getTextView().search(pattern, true, false, false, false) != 0) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            myFBReaderApp.showPopup(popup.getId());
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            UIUtil.showErrorMessage(FBReader.this, "textNotFound");
                            popup.StartPosition = null;
                        }
                    });
                }
            }
        };
        UIUtil.wait("search", runnable, this);
    } else if (FBReaderIntents.Action.CLOSE.equals(intent.getAction())) {
        myCancelIntent = intent;
        myOpenBookIntent = null;
    } else if (FBReaderIntents.Action.PLUGIN_CRASH.equals(intent.getAction())) {
        final Book book = FBReaderIntents.getBookExtra(intent);
        myFBReaderApp.ExternalBook = null;
        myOpenBookIntent = null;
        getCollection().bindToService(this, new Runnable() {
            public void run() {
                Book b = myFBReaderApp.Collection.getRecentBook(0);
                if (b.equals(book)) {
                    b = myFBReaderApp.Collection.getRecentBook(1);
                }
                myFBReaderApp.openBook(b, null, null, FBReader.this);
            }
        });
    } else {
        super.onNewIntent(intent);
    }
}

From source file:org.bohrmeista.chan.ui.activity.BoardActivity.java

/**
 * Handle opening from an external url./*from w  w  w  .j  a v a2 s. c  o  m*/
 *
 * @param startUri
 */
private void handleIntentURI(Uri startUri) {
    Logger.d(TAG, "Opening " + startUri.getPath());

    List<String> parts = startUri.getPathSegments();

    if (parts.size() == 1) {
        // Board mode
        String rawBoard = parts.get(0);
        startLoadingBoard(new Loadable(rawBoard));
    } else if (parts.size() >= 3) {
        // Thread mode
        String rawBoard = parts.get(0);
        int no = -1;

        try {
            Matcher matcher = THREAD_URL_PATTERN.matcher(parts.get(2));
            if (matcher.find())
                no = Integer.parseInt(matcher.group(1));
        } catch (NumberFormatException e) {
        }

        int post = -1;
        String fragment = startUri.getFragment();
        if (fragment != null) {
            int index = fragment.indexOf("p");
            if (index >= 0) {
                try {
                    post = Integer.parseInt(fragment.substring(index + 1));
                } catch (NumberFormatException e) {
                }
            }
        }

        if (no >= 0) {
            startLoadingThread(new Loadable(rawBoard, no));
            if (post >= 0) {
                threadFragment.highlightPost(post);
            }
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else {
        showUrlOpenPicker(startUri.toString());
    }
}

From source file:org.wingy.jp8chan.ui.activity.BoardActivity.java

/**
 * Handle opening from an external url./*  w  ww.j a v a2s . c om*/
 *
 * @param startUri
 */
private void handleIntentURI(Uri startUri) {
    Logger.d(TAG, "Opening " + startUri.getPath());

    List<String> parts = startUri.getPathSegments();

    if (parts.size() == 1) {
        // Board mode
        String rawBoard = parts.get(0);
        startLoadingBoard(new Loadable(rawBoard));
    } else if (parts.size() >= 3) {
        // Thread mode
        String rawBoard = parts.get(0);
        int no = -1;

        try {
            Matcher matcher = THREAD_URL_PATTERN.matcher(parts.get(2));
            if (matcher.find())
                no = Integer.parseInt(matcher.group(1));
        } catch (NumberFormatException e) {
        }

        int post = -1;
        String fragment = startUri.getFragment();
        if (fragment != null) {
            //int index = fragment.indexOf("q");
            //if (index >= 0) {
            try {
                post = Integer.parseInt(fragment);
            } catch (NumberFormatException e) {
            }
            //}
        }

        if (no >= 0) {
            startLoadingThread(new Loadable(rawBoard, no));
            if (post >= 0) {
                threadFragment.highlightPost(post);
            }
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else {
        showUrlOpenPicker(startUri.toString());
    }
}

From source file:org.floens.chan.ui.activity.ChanActivity.java

/**
 * Handle opening from an external url./*from w w  w.j a v a 2s. c om*/
 *
 * @param startUri
 */
private void handleIntentURI(Uri startUri) {
    Logger.d(TAG, "Opening " + startUri.getPath());

    List<String> parts = startUri.getPathSegments();

    if (parts.size() == 1) {
        // Board mode
        String rawBoard = parts.get(0);
        if (ChanApplication.getBoardManager().getBoardExists(rawBoard)) {
            startLoadingBoard(new Loadable(rawBoard));
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else if (parts.size() >= 3) {
        // Thread mode
        String rawBoard = parts.get(0);
        int no = -1;

        try {
            no = Integer.parseInt(parts.get(2));
        } catch (NumberFormatException e) {
        }

        int post = -1;
        String fragment = startUri.getFragment();
        if (fragment != null) {
            int index = fragment.indexOf("p");
            if (index >= 0) {
                try {
                    post = Integer.parseInt(fragment.substring(index + 1));
                } catch (NumberFormatException e) {
                }
            }
        }

        if (no >= 0 && ChanApplication.getBoardManager().getBoardExists(rawBoard)) {
            startLoadingThread(new Loadable(rawBoard, no));
            if (post >= 0) {
                threadFragment.highlightPost(post);
            }
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else {
        showUrlOpenPicker(startUri.toString());
    }
}

From source file:org.connectbot.ConsoleFragment.java

protected void startConsole(Uri requested) {
    /*super.onNewIntent(intent);
            /*from w  w w.  j av  a2 s  .  c om*/
    Log.d(TAG, "onNewIntent called");
            
    requested = intent.getData();
            
    if (requested == null) {
       Log.e(TAG, "Got null intent data in onNewIntent()");
       return;
    }
            
    if (bound == null) {
       Log.e(TAG, "We're not bound in onNewIntent()");
       return;
    }*/

    TerminalBridge requestedBridge = mListener.getTerminalManager().getConnectedBridge(requested.getFragment());
    int requestedIndex = 0;

    synchronized (flip) {
        if (requestedBridge == null) {
            // If we didn't find the requested connection, try opening it

            try {
                Log.d(TAG,
                        String.format(
                                "We couldnt find an existing bridge with URI=%s (nickname=%s),"
                                        + "so creating one now",
                                requested.toString(), requested.getFragment()));
                requestedBridge = mListener.getTerminalManager().openConnection(requested);
            } catch (Exception e) {
                Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
                // TODO: We should display an error dialog here.
                return;
            }

            requestedIndex = addNewTerminalView(requestedBridge);
        } else {
            final int flipIndex = getFlipIndex(requestedBridge);
            if (flipIndex > requestedIndex) {
                requestedIndex = flipIndex;
            }
        }

        setDisplayedTerminal(requestedIndex);
    }
}

From source file:org.opendatakit.survey.activities.MainMenuActivity.java

private void transitionToFormHelper(Uri uri, FormIdStruct newForm) {
    // work through switching to that form
    setAppName(newForm.appName);//w w w .j  a  va2  s.  c  om
    setCurrentForm(newForm);
    clearSectionScreenState();
    String fragment = uri.getFragment();
    if (fragment != null && fragment.length() != 0) {
        // and process the fragment to find the instanceId, screenPath and other
        // kv pairs
        String[] pargs = fragment.split("&");
        boolean first = true;
        StringBuilder b = new StringBuilder();
        int i;
        for (i = 0; i < pargs.length; ++i) {
            String[] keyValue = pargs[i].split("=");
            if ("instanceId".equals(keyValue[0])) {
                if (keyValue.length == 2) {
                    setInstanceId(StringEscapeUtils.unescapeHtml4(keyValue[1]));
                }
            } else if ("screenPath".equals(keyValue[0])) {
                if (keyValue.length == 2) {
                    setSectionScreenState(StringEscapeUtils.unescapeHtml4(keyValue[1]), null);
                }
            } else if ("refId".equals(keyValue[0]) || "formPath".equals(keyValue[0])) {
                // ignore
            } else {
                if (!first) {
                    b.append("&");
                }
                first = false;
                b.append(pargs[i]);
            }
        }
        String aux = b.toString();
        if (aux.length() != 0) {
            setAuxillaryHash(aux);
        }
    } else {
        setInstanceId(null);
        setAuxillaryHash(null);
    }
    currentFragment = ScreenList.WEBKIT;
}

From source file:net.wequick.small.webkit.WebView.java

private void initSettings() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString(webSettings.getUserAgentString() + " Native");
    this.addJavascriptInterface(new SmallJsBridge(), "_Small");

    this.setWebChromeClient(new WebChromeClient() {
        @Override/* w  ww. j  a  v  a  2s . c  o  m*/
        public void onReceivedTitle(android.webkit.WebView view, String title) {
            // Call if html title is set
            super.onReceivedTitle(view, title);
            mTitle = title;
            WebActivity activity = (WebActivity) WebViewPool.getContext(view);
            if (activity != null) {
                activity.setTitle(title);
            }
            // May receive head meta at the same time
            initMetas();
        }

        @Override
        public boolean onJsAlert(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            if (context == null)
                return false;

            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.cancel();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = consoleMessage.message();
            if (msg == null)
                return false;
            Uri uri = Uri.parse(msg);
            if (uri != null && null != uri.getScheme() && uri.getScheme().equals(SMALL_SCHEME)) {
                String host = uri.getHost();
                String ret = uri.getQueryParameter(SMALL_QUERY_KEY_RET);
                if (host.equals(SMALL_HOST_POP)) {
                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                } else if (host.equals(SMALL_HOST_EXEC)) {
                    if (mOnResultListener != null) {
                        mOnResultListener.onResult(ret);
                    }
                }
                return true;
            }
            Log.d(consoleMessage.sourceId(),
                    "line" + consoleMessage.lineNumber() + ": " + consoleMessage.message());
            return true;
        }

        @Override
        public void onCloseWindow(android.webkit.WebView window) {
            super.onCloseWindow(window);
            close(new OnResultListener() {
                @Override
                public void onResult(String ret) {
                    if (ret.equals("false"))
                        return;

                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                }
            });
        }
    });

    this.setWebViewClient(new android.webkit.WebViewClient() {

        private final String ANCHOR_SCHEME = "anchor";

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                return super.shouldOverrideUrlLoading(view, url);
            }

            Boolean hasStarted = mHasStartedUrl.get(url);
            if (hasStarted != null && hasStarted) {
                // location redirected before page finished
                return super.shouldOverrideUrlLoading(view, url);
            }

            HitTestResult hit = view.getHitTestResult();
            if (hit != null) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals(ANCHOR_SCHEME)) {
                    // Scroll to anchor
                    int anchorY = Integer.parseInt(uri.getHost());
                    view.scrollTo(0, anchorY);
                } else {
                    Small.openUri(uri, WebViewPool.getContext(view));
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mHasStartedUrl.put(url, true);

            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                mInjected = false;
            }
            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageStarted(WebViewPool.getContext(view), (WebView) view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            super.onPageFinished(view, url);
            mHasStartedUrl.remove(url);

            HitTestResult hit = view.getHitTestResult();
            if (hit != null && hit.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
                // Triggered by user clicked
                Uri uri = Uri.parse(url);
                String anchor = uri.getFragment();
                if (anchor != null) {
                    // If is an anchor, calculate the content offset by DOM
                    // and call native to adjust WebView's offset
                    view.loadUrl(JS_PREFIX + "var y=document.body.scrollTop;"
                            + "var e=document.getElementsByName('" + anchor + "')[0];" + "while(e){"
                            + "y+=e.offsetTop-e.scrollTop+e.clientTop;e=e.offsetParent;}" + "location='"
                            + ANCHOR_SCHEME + "://'+y;");
                }
            }

            if (!mInjected) {
                // Re-inject Small Js
                loadJs(SMALL_INJECT_JS);
                initMetas();
                mInjected = true;
            }

            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageFinished(WebViewPool.getContext(view), (WebView) view, url);
            }
        }

        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e("Web", "error: " + description);
            if (sWebViewClient != null && failingUrl.equals(mLoadingUrl)) {
                sWebViewClient.onReceivedError(WebViewPool.getContext(view), (WebView) view, errorCode,
                        description, failingUrl);
            }
        }
    });
}