Example usage for android.net Uri getScheme

List of usage examples for android.net Uri getScheme

Introduction

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

Prototype

@Nullable
public abstract String getScheme();

Source Link

Document

Gets the scheme of this URI.

Usage

From source file:com.lgallardo.qbittorrentclient.RefreshListener.java

public static String getFilePathFromUri(Context c, Uri uri) {
    String filePath = null;/*from   w  ww  . j  a  va 2s .c  o  m*/
    if ("content".equals(uri.getScheme())) {
        String[] filePathColumn = { MediaStore.MediaColumns.DATA };
        ContentResolver contentResolver = c.getContentResolver();

        Cursor cursor = contentResolver.query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        }
    } else if ("file".equals(uri.getScheme())) {
        filePath = new File(uri.getPath()).getAbsolutePath();
    }
    return filePath;
}

From source file:com.igniva.filemanager.fragments.ZipViewer.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    s = getArguments().getString("path");
    Uri uri = Uri.parse(s);
    f = new File(uri.getPath());
    mToolbarContainer = getActivity().findViewById(R.id.lin);
    mToolbarContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override//from   w w w .  ja va  2s  . co  m
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (stopAnims) {
                if ((!rarAdapter.stoppedAnimation)) {
                    stopAnim();
                }
                rarAdapter.stoppedAnimation = true;

            }
            stopAnims = false;
            return false;
        }
    });
    hidemode = Sp.getInt("hidemode", 0);
    listView.setVisibility(View.VISIBLE);
    mLayoutManager = new LinearLayoutManager(getActivity());
    listView.setLayoutManager(mLayoutManager);
    res = getResources();
    mainActivity.supportInvalidateOptionsMenu();
    if (mainActivity.theme1 == 1)
        rootView.setBackgroundColor(getResources().getColor(R.color.holo_dark_background));
    else
        listView.setBackgroundColor(getResources().getColor(android.R.color.background_light));

    gobackitem = Sp.getBoolean("goBack_checkbox", false);
    coloriseIcons = Sp.getBoolean("coloriseIcons", true);
    Calendar calendar = Calendar.getInstance();
    showSize = Sp.getBoolean("showFileSize", false);
    showLastModified = Sp.getBoolean("showLastModified", true);
    showDividers = Sp.getBoolean("showDividers", true);
    year = ("" + calendar.get(Calendar.YEAR)).substring(2, 4);
    skin = PreferenceUtils.getPrimaryColorString(Sp);
    accentColor = PreferenceUtils.getAccentString(Sp);
    iconskin = PreferenceUtils.getFolderColorString(Sp);

    theme = Integer.parseInt(Sp.getString("theme", "0"));
    theme1 = theme == 2 ? PreferenceUtils.hourOfDay() : theme;

    //mainActivity.findViewById(R.id.buttonbarframe).setBackgroundColor(Color.parseColor(skin));

    files = new ArrayList<>();
    if (savedInstanceState == null && f != null) {
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(null);
        } else {
            openmode = 0;
            SetupZip(null);
        }
    } else {
        f = new File(savedInstanceState.getString("file"));
        s = savedInstanceState.getString("uri");
        uri = Uri.parse(s);
        f = new File(uri.getPath());
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(savedInstanceState);
        } else {
            openmode = 0;
            SetupZip(savedInstanceState);
        }

    }
    String fileName = null;
    try {
        if (uri.getScheme().equals("file")) {
            fileName = uri.getLastPathSegment();
        } else {
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri,
                        new String[] { MediaStore.Images.ImageColumns.DISPLAY_NAME }, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor
                            .getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
                }
            } finally {

                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (fileName == null || fileName.trim().length() == 0)
        fileName = f.getName();
    try {
        mainActivity.setActionBarTitle(fileName);
    } catch (Exception e) {
        mainActivity.setActionBarTitle(getResources().getString(R.string.zip_viewer));
    }
    mainActivity.supportInvalidateOptionsMenu();
    mToolbarHeight = getToolbarHeight(getActivity());
    paddingTop = (mToolbarHeight) + dpToPx(72);
    mToolbarContainer.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    paddingTop = mToolbarContainer.getHeight();
                    mToolbarHeight = mainActivity.toolbar.getHeight();

                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }

            });

}

From source file:androidx.media.widget.VideoView2.java

private void openVideo(Uri uri, Map<String, String> headers) {
    resetPlayer();//  w  w w .  ja  va2s  .  co m
    if (isRemotePlayback()) {
        // TODO (b/77158231)
        // mRoutePlayer.openVideo(dsd);
        return;
    }

    try {
        Log.d(TAG, "openVideo(): creating new MediaPlayer instance.");
        mMediaPlayer = new MediaPlayer();
        mSurfaceView.setMediaPlayer(mMediaPlayer);
        mTextureView.setMediaPlayer(mMediaPlayer);
        mCurrentView.assignSurfaceToMediaPlayer(mMediaPlayer);

        final Context context = getContext();
        // TODO: Add timely firing logic for more accurate sync between CC and video frame
        // mSubtitleController = new SubtitleController(context);
        // mSubtitleController.registerRenderer(new ClosedCaptionRenderer(context));
        // mSubtitleController.setAnchor((SubtitleController.Anchor) mSubtitleView);

        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);

        mCurrentBufferPercentage = -1;
        mMediaPlayer.setDataSource(getContext(), uri, headers);
        mMediaPlayer.setAudioAttributes(mAudioAttributes);
        // mMediaPlayer.setOnSubtitleDataListener(mSubtitleListener);
        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        mMediaPlayer.prepareAsync();

        // Save file name as title since the file may not have a title Metadata.
        mTitle = uri.getPath();
        String scheme = uri.getScheme();
        if (scheme != null && scheme.equals("file")) {
            mTitle = uri.getLastPathSegment();
        }
        mRetriever = new MediaMetadataRetriever();
        mRetriever.setDataSource(getContext(), uri);

        if (DEBUG) {
            Log.d(TAG, "openVideo(). mCurrentState=" + mCurrentState + ", mTargetState=" + mTargetState);
        }
    } catch (IOException | IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + uri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, MediaPlayer.MEDIA_ERROR_IO);
    }
}

From source file:com.amaze.carbonfilemanager.fragments.ZipViewer.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    s = getArguments().getString(KEY_PATH);
    Uri uri = Uri.parse(s);
    f = new File(uri.getPath());
    mToolbarContainer = getActivity().findViewById(R.id.lin);
    mToolbarContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override//from w w  w .  j  ava  2s. c  om
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (stopAnims) {
                if ((!rarAdapter.stoppedAnimation)) {
                    stopAnim();
                }
                rarAdapter.stoppedAnimation = true;

            }
            stopAnims = false;
            return false;
        }
    });
    hidemode = Sp.getInt("hidemode", 0);
    listView.setVisibility(View.VISIBLE);
    mLayoutManager = new LinearLayoutManager(getActivity());
    listView.setLayoutManager(mLayoutManager);
    res = getResources();
    mainActivity.supportInvalidateOptionsMenu();
    if (utilsProvider.getAppTheme().equals(AppTheme.DARK))
        rootView.setBackgroundColor(Utils.getColor(getContext(), R.color.holo_dark_background));
    else
        listView.setBackgroundColor(Utils.getColor(getContext(), android.R.color.background_light));

    gobackitem = Sp.getBoolean("goBack_checkbox", false);
    coloriseIcons = Sp.getBoolean("coloriseIcons", true);
    Calendar calendar = Calendar.getInstance();
    showSize = Sp.getBoolean("showFileSize", false);
    showLastModified = Sp.getBoolean("showLastModified", true);
    showDividers = Sp.getBoolean("showDividers", true);
    year = ("" + calendar.get(Calendar.YEAR)).substring(2, 4);
    skin = mainActivity.getColorPreference().getColorAsString(ColorUsage.PRIMARY);
    accentColor = mainActivity.getColorPreference().getColorAsString(ColorUsage.ACCENT);
    iconskin = mainActivity.getColorPreference().getColorAsString(ColorUsage.ICON_SKIN);

    //mainActivity.findViewById(R.id.buttonbarframe).setBackgroundColor(Color.parseColor(skin));

    if (savedInstanceState == null && f != null) {

        files = new ArrayList<>();
        // adding a cache file to delete where any user interaction elements will be cached
        String fileName = f.getName().substring(0, f.getName().lastIndexOf("."));
        files.add(new BaseFile(getActivity().getExternalCacheDir().getPath() + "/" + fileName));
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(null);
        } else {
            openmode = 0;
            SetupZip(null);
        }
    } else {

        f = new File(savedInstanceState.getString(KEY_FILE));
        s = savedInstanceState.getString(KEY_URI);
        uri = Uri.parse(s);
        f = new File(uri.getPath());
        files = savedInstanceState.getParcelableArrayList(KEY_CACHE_FILES);
        isOpen = savedInstanceState.getBoolean(KEY_OPEN);
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(savedInstanceState);
        } else {
            openmode = 0;
            SetupZip(savedInstanceState);
        }

    }
    String fileName = null;
    try {
        if (uri.getScheme().equals(KEY_FILE)) {
            fileName = uri.getLastPathSegment();
        } else {
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri,
                        new String[] { MediaStore.Images.ImageColumns.DISPLAY_NAME }, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor
                            .getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
                }
            } finally {

                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (fileName == null || fileName.trim().length() == 0)
        fileName = f.getName();
    try {
        mainActivity.setActionBarTitle(fileName);
    } catch (Exception e) {
        mainActivity.setActionBarTitle(getResources().getString(R.string.zip_viewer));
    }
    mainActivity.supportInvalidateOptionsMenu();
    mToolbarHeight = getToolbarHeight(getActivity());
    paddingTop = (mToolbarHeight) + dpToPx(72);
    mToolbarContainer.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    paddingTop = mToolbarContainer.getHeight();
                    mToolbarHeight = mainActivity.toolbar.getHeight();

                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }

            });

}

From source file:com.android.mail.compose.ComposeActivity.java

/**
 * Fill all the widgets with the content found in the Intent Extra, if any.
 * Also apply the same style to all widgets. Note: if initFromExtras is
 * called as a result of switching between reply, reply all, and forward per
 * the latest revision of Gmail, and the user has already made changes to
 * attachments on a previous incarnation of the message (as a reply, reply
 * all, or forward), the original attachments from the message will not be
 * re-instantiated. The user's changes will be respected. This follows the
 * web gmail interaction./*from w ww  . j av a  2 s .com*/
 * @return {@code true} if the activity should not call {@link #finishSetup}.
 */
public boolean initFromExtras(Intent intent) {
    // If we were invoked with a SENDTO intent, the value
    // should take precedence
    final Uri dataUri = intent.getData();
    if (dataUri != null) {
        if (MAIL_TO.equals(dataUri.getScheme())) {
            initFromMailTo(dataUri.toString());
        } else {
            if (!mAccount.composeIntentUri.equals(dataUri)) {
                String toText = dataUri.getSchemeSpecificPart();
                if (toText != null) {
                    mTo.setText("");
                    addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
                }
            }
        }
    }

    String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
    if (extraStrings != null) {
        addToAddresses(Arrays.asList(extraStrings));
    }
    extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
    if (extraStrings != null) {
        addCcAddresses(Arrays.asList(extraStrings), null);
    }
    extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
    if (extraStrings != null) {
        addBccAddresses(Arrays.asList(extraStrings));
    }

    String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
    if (extraString != null) {
        mSubject.setText(extraString);
    }

    for (String extra : ALL_EXTRAS) {
        if (intent.hasExtra(extra)) {
            String value = intent.getStringExtra(extra);
            if (EXTRA_TO.equals(extra)) {
                addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
            } else if (EXTRA_CC.equals(extra)) {
                addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
            } else if (EXTRA_BCC.equals(extra)) {
                addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
            } else if (EXTRA_SUBJECT.equals(extra)) {
                mSubject.setText(value);
            } else if (EXTRA_BODY.equals(extra)) {
                setBody(value, true /* with signature */);
            } else if (EXTRA_QUOTED_TEXT.equals(extra)) {
                initQuotedText(value, true /* shouldQuoteText */);
            }
        }
    }

    Bundle extras = intent.getExtras();
    if (extras != null) {
        CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
        setBody((text != null) ? text : "", true /* with signature */);

        // TODO - support EXTRA_HTML_TEXT
    }

    mExtraValues = intent.getParcelableExtra(EXTRA_VALUES);
    if (mExtraValues != null) {
        LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString());
        initExtraValues(mExtraValues);
        return true;
    }

    return false;
}

From source file:com.android.mail.compose.ComposeActivity.java

/**
 * Helper function to handle a list of uris to attach.
 * @return the total size of all successfully attached files.
 *///from   w w  w  . j  a v  a2s . c om
private long handleAttachmentUrisFromIntent(List<Uri> uris) {
    ArrayList<Attachment> attachments = Lists.newArrayList();
    for (Uri uri : uris) {
        try {
            if (uri != null) {
                if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
                    // We must not allow files from /data, even from our process.
                    final File f = new File(uri.getPath());
                    final String filePath = f.getCanonicalPath();
                    if (filePath.startsWith(DATA_DIRECTORY_ROOT)) {
                        showErrorToast(getString(R.string.attachment_permission_denied));
                        Analytics.getInstance().sendEvent(ANALYTICS_CATEGORY_ERRORS, "send_intent_attachment",
                                "data_dir", 0);
                        continue;
                    }
                } else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
                    // disallow attachments from our own EmailProvider (b/27308057)
                    if (getEmailProviderAuthority().equals(uri.getAuthority())) {
                        showErrorToast(getString(R.string.attachment_permission_denied));
                        Analytics.getInstance().sendEvent(ANALYTICS_CATEGORY_ERRORS, "send_intent_attachment",
                                "email_provider", 0);
                        continue;
                    }
                }

                if (!handleSpecialAttachmentUri(uri)) {
                    final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
                    attachments.add(a);

                    Analytics.getInstance().sendEvent("send_intent_attachment",
                            Utils.normalizeMimeType(a.getContentType()), null, a.size);
                }
            }
        } catch (AttachmentFailureException e) {
            LogUtils.e(LOG_TAG, e, "Error adding attachment");
            showAttachmentTooBigToast(e.getErrorRes());
        } catch (IOException | SecurityException e) {
            LogUtils.e(LOG_TAG, e, "Error adding attachment");
            showErrorToast(getString(R.string.attachment_permission_denied));
        }
    }
    return addAttachments(attachments);
}

From source file:com.gelakinetic.mtgfam.FamiliarActivity.java

private boolean processIntent(Intent intent) {
    boolean isDeepLink = false;

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        /* Do a search by name, launched from the quick search */
        String query = intent.getStringExtra(SearchManager.QUERY);
        Bundle args = new Bundle();
        SearchCriteria sc = new SearchCriteria();
        sc.name = query;//from   w w w . j ava2 s. co m
        args.putSerializable(SearchViewFragment.CRITERIA, sc);
        selectItem(R.string.main_card_search, args, false,
                true); /* Don't clear backstack, do force the intent */

    } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {

        boolean shouldSelectItem = true;

        Uri data = intent.getData();
        Bundle args = new Bundle();
        assert data != null;

        boolean shouldClearFragmentStack = true; /* Clear backstack for deep links */
        if (data.getAuthority().toLowerCase().contains("gatherer.wizards")) {
            SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false);
            try {
                String queryParam;
                if ((queryParam = data.getQueryParameter("multiverseid")) != null) {
                    Cursor cursor = CardDbAdapter.fetchCardByMultiverseId(Long.parseLong(queryParam),
                            new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID },
                            database);
                    if (cursor.getCount() != 0) {
                        isDeepLink = true;
                        args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                                new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) });
                    }
                    cursor.close();
                    if (args.size() == 0) {
                        throw new Exception("Not Found");
                    }
                } else if ((queryParam = data.getQueryParameter("name")) != null) {
                    Cursor cursor = CardDbAdapter.fetchCardByName(queryParam,
                            new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID },
                            true, database);
                    if (cursor.getCount() != 0) {
                        isDeepLink = true;
                        args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                                new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) });
                    }
                    cursor.close();
                    if (args.size() == 0) {
                        throw new Exception("Not Found");
                    }
                } else {
                    throw new Exception("Not Found");
                }
            } catch (Exception e) {
                /* empty cursor, just return */
                ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show();
                this.finish();
                shouldSelectItem = false;
            } finally {
                DatabaseManager.getInstance(this, false).closeDatabase(false);
            }
        } else if (data.getAuthority().contains("CardSearchProvider")) {
            /* User clicked a card in the quick search autocomplete, jump right to it */
            args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                    new long[] { Long.parseLong(data.getLastPathSegment()) });
            shouldClearFragmentStack = false; /* Don't clear backstack for search intents */
        } else {
            /* User clicked a deep link, jump to the card(s) */
            isDeepLink = true;

            SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false);
            try {
                Cursor cursor = null;
                boolean screenLaunched = false;
                if (data.getScheme().toLowerCase().equals("card")
                        && data.getAuthority().toLowerCase().equals("multiverseid")) {
                    if (data.getLastPathSegment() == null) {
                        /* Home screen deep link */
                        launchHomeScreen();
                        screenLaunched = true;
                        shouldSelectItem = false;
                    } else {
                        try {
                            /* Don't clear the fragment stack for internal links (thanks Meld cards) */
                            if (data.getPathSegments().contains("internal")) {
                                shouldClearFragmentStack = false;
                            }
                            cursor = CardDbAdapter.fetchCardByMultiverseId(
                                    Long.parseLong(data.getLastPathSegment()),
                                    new String[] {
                                            CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID },
                                    database);
                        } catch (NumberFormatException e) {
                            cursor = null;
                        }
                    }
                }

                if (cursor != null) {
                    if (cursor.getCount() != 0) {
                        args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                                new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) });
                    } else {
                        /* empty cursor, just return */
                        ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show();
                        this.finish();
                        shouldSelectItem = false;
                    }
                    cursor.close();
                } else if (!screenLaunched) {
                    /* null cursor, just return */
                    ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show();
                    this.finish();
                    shouldSelectItem = false;
                }
            } catch (FamiliarDbException e) {
                e.printStackTrace();
            }
            DatabaseManager.getInstance(this, false).closeDatabase(false);
        }
        args.putInt(CardViewPagerFragment.STARTING_CARD_POSITION, 0);
        if (shouldSelectItem) {
            selectItem(R.string.main_card_search, args, shouldClearFragmentStack, true);
        }
    } else if (ACTION_ROUND_TIMER.equals(intent.getAction())) {
        selectItem(R.string.main_timer, null, true, false);
    } else if (ACTION_CARD_SEARCH.equals(intent.getAction())) {
        selectItem(R.string.main_card_search, null, true, false);
    } else if (ACTION_LIFE.equals(intent.getAction())) {
        selectItem(R.string.main_life_counter, null, true, false);
    } else if (ACTION_DICE.equals(intent.getAction())) {
        selectItem(R.string.main_dice, null, true, false);
    } else if (ACTION_TRADE.equals(intent.getAction())) {
        selectItem(R.string.main_trade, null, true, false);
    } else if (ACTION_MANA.equals(intent.getAction())) {
        selectItem(R.string.main_mana_pool, null, true, false);
    } else if (ACTION_WISH.equals(intent.getAction())) {
        selectItem(R.string.main_wishlist, null, true, false);
    } else if (ACTION_RULES.equals(intent.getAction())) {
        selectItem(R.string.main_rules, null, true, false);
    } else if (ACTION_JUDGE.equals(intent.getAction())) {
        selectItem(R.string.main_judges_corner, null, true, false);
    } else if (ACTION_MOJHOSTO.equals(intent.getAction())) {
        selectItem(R.string.main_mojhosto, null, true, false);
    } else if (ACTION_PROFILE.equals(intent.getAction())) {
        selectItem(R.string.main_profile, null, true, false);
    } else if (ACTION_DECKLIST.equals(intent.getAction())) {
        selectItem(R.string.main_decklist, null, true, false);
    } else if (Intent.ACTION_MAIN.equals(intent.getAction())) {
        /* App launched as regular, show the default fragment if there isn't one already */
        if (getSupportFragmentManager().getFragments() == null) {
            launchHomeScreen();
        }
    } else {
        /* Some unknown intent, just finish */
        finish();
    }

    mDrawerList.setItemChecked(mCurrentFrag, true);
    return isDeepLink;
}

From source file:cgeo.geocaching.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*w  ww .  j a  v  a  2 s  . co  m*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    String cookiesDone = CookieJar.getCookiesAsString(prefs);

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            CookieJar.setCookies(prefs, uc);

            InputStream ins = getInputstreamFromConnection(connection);
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr, 16 * 1024);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(cgSettings.tag + "|" + requestId,
                    "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer.length() > 0) {
            break;
        }
    }

    cgResponse response = new cgResponse();

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative()) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (StringUtils.isNotEmpty(buffer)) {
                replaceWhitespace(buffer);
                String data = buffer.toString();
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:com.irccloud.android.activity.MainActivity.java

private boolean open_uri(Uri uri) {
    if (uri != null && conn != null && conn.ready) {
        launchURI = null;/*from   w  w  w . j  a v  a2s .  c  o m*/
        ServersDataSource.Server s = null;
        try {
            if (uri.getHost().equals("cid")) {
                s = ServersDataSource.getInstance().getServer(Integer.parseInt(uri.getPathSegments().get(0)));
            }
        } catch (NumberFormatException e) {

        }
        if (s == null) {
            if (uri.getPort() > 0)
                s = ServersDataSource.getInstance().getServer(uri.getHost(), uri.getPort());
            else if (uri.getScheme() != null && uri.getScheme().equalsIgnoreCase("ircs"))
                s = ServersDataSource.getInstance().getServer(uri.getHost(), true);
            else
                s = ServersDataSource.getInstance().getServer(uri.getHost());
        }

        if (s != null) {
            if (uri.getPath() != null && uri.getPath().length() > 1) {
                String key = null;
                String channel = uri.getLastPathSegment();
                if (channel.contains(",")) {
                    key = channel.substring(channel.indexOf(",") + 1);
                    channel = channel.substring(0, channel.indexOf(","));
                }
                BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, channel);
                if (b != null) {
                    server = null;
                    return open_bid(b.bid);
                } else {
                    onBufferSelected(-1);
                    title.setText(channel);
                    getSupportActionBar().setTitle(channel);
                    bufferToOpen = channel;
                    conn.join(s.cid, channel, key);
                }
                return true;
            } else {
                BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, "*");
                if (b != null)
                    return open_bid(b.bid);
            }
        } else {
            if (!getResources().getBoolean(R.bool.isTablet)) {
                Intent i = new Intent(this, EditConnectionActivity.class);
                i.putExtra("hostname", uri.getHost());
                if (uri.getPort() > 0)
                    i.putExtra("port", uri.getPort());
                else if (uri.getScheme().equalsIgnoreCase("ircs"))
                    i.putExtra("port", 6697);
                if (uri.getPath() != null && uri.getPath().length() > 1)
                    i.putExtra("channels", uri.getPath().substring(1).replace(",", " "));
                startActivity(i);
            } else {
                EditConnectionFragment connFragment = new EditConnectionFragment();
                connFragment.default_hostname = uri.getHost();
                if (uri.getPort() > 0)
                    connFragment.default_port = uri.getPort();
                else if (uri.getScheme().equalsIgnoreCase("ircs"))
                    connFragment.default_port = 6697;
                if (uri.getPath() != null && uri.getPath().length() > 1)
                    connFragment.default_channels = uri.getPath().substring(1).replace(",", " ");
                connFragment.show(getSupportFragmentManager(), "addnetwork");
            }
            return true;
        }
    }
    return false;
}