Example usage for android.content Intent hasExtra

List of usage examples for android.content Intent hasExtra

Introduction

In this page you can find the example usage for android.content Intent hasExtra.

Prototype

public boolean hasExtra(String name) 

Source Link

Document

Returns true if an extra value is associated with the given name.

Usage

From source file:com.mobicage.rogerthat.plugins.scan.ProcessScanActivity.java

private SafeBroadcastReceiver getBroadcastReceiver() {
    return new SafeBroadcastReceiver() {
        @Override/*from w ww  .  j  a  v a2 s. co  m*/
        public String[] onSafeReceive(Context context, Intent intent) {
            T.UI();
            if (intent.getAction().equals(FriendsPlugin.FRIEND_INFO_RECEIVED_INTENT)) {
                final String emailHash = intent.getStringExtra(EMAILHASH);
                if (emailHash != null && emailHash.equals(mExpectedEmailHash)) {
                    abortProcessing();

                    if (intent.getBooleanExtra(ProcessScanActivity.SUCCESS, true)) {
                        final Intent inviteFriendIntent = new Intent(ProcessScanActivity.this,
                                InviteFriendActivity.class);
                        // Copy extra from other intent
                        for (String extra : new String[] { AVATAR, DESCRIPTION, DESCRIPTION_BRANDING, EMAIL,
                                EMAILHASH, NAME, QUALIFIED_IDENTIFIER }) {
                            inviteFriendIntent.putExtra(extra, intent.getStringExtra(extra));
                        }
                        inviteFriendIntent.putExtra(TYPE,
                                intent.getLongExtra(TYPE, FriendsPlugin.FRIEND_TYPE_USER));
                        startActivity(inviteFriendIntent);
                        finish();
                        return new String[] { intent.getAction() };
                    } else {
                        showError(intent);
                    }

                } else {
                    // ignore
                }
            } else if (intent.getAction().equals(FriendsPlugin.SERVICE_ACTION_INFO_RECEIVED_INTENT)) {
                if (mExpectedEmailHash != null && mExpectedEmailHash.equals(intent.getStringExtra(EMAILHASH))
                        && mExpectedAction != null
                        && mExpectedAction.equals(intent.getStringExtra(POKE_ACTION))) {
                    abortProcessing();

                    if (intent.getBooleanExtra(SUCCESS, true)) {
                        final Intent serviceActionIntent = new Intent(ProcessScanActivity.this,
                                ServiceActionActivity.class);
                        // Copy extra from other intent
                        for (String extra : new String[] { AVATAR, DESCRIPTION, DESCRIPTION_BRANDING, EMAIL,
                                NAME, POKE_DESCRIPTION, QUALIFIED_IDENTIFIER, STATIC_FLOW, STATIC_FLOW_HASH }) {
                            serviceActionIntent.putExtra(extra, intent.getStringExtra(extra));
                        }
                        serviceActionIntent.putExtra(EMAILHASH, mExpectedEmailHash);
                        serviceActionIntent.putExtra(POKE_ACTION, mExpectedAction);
                        serviceActionIntent.setAction(FriendsPlugin.SERVICE_ACTION_INFO_RECEIVED_INTENT);
                        serviceActionIntent.putExtra(SUCCESS, true);
                        startActivity(serviceActionIntent);
                        finish();
                        // TODO: set success?

                        return new String[] { intent.getAction() };
                    } else {
                        showError(intent);
                    }
                } else {
                    // ignore
                }
            } else if (intent.getAction().equals(URL_REDIRECTION_DONE)) {
                final String emailHash = intent.getStringExtra(EMAILHASH);
                if (intent.hasExtra(POKE_ACTION)) {
                    final String pokeAction = intent.getStringExtra(POKE_ACTION);
                    getServiceActionInfo(emailHash, pokeAction);
                } else {
                    processEmailHash(emailHash);
                }
                return new String[] { intent.getAction() };
            }

            return null; // Intent was ignored
        }

    };
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT);
    if (theme.equals("black")) {
        setTheme(R.style.TuskyDialogActivityBlackTheme);
    }/*w  ww  .  j  a  v a2 s.c om*/
    setContentView(R.layout.activity_compose);

    replyTextView = findViewById(R.id.composeReplyView);
    replyContentTextView = findViewById(R.id.composeReplyContentView);
    textEditor = findViewById(R.id.composeEditField);
    mediaPreviewBar = findViewById(R.id.compose_media_preview_bar);
    contentWarningBar = findViewById(R.id.composeContentWarningBar);
    contentWarningEditor = findViewById(R.id.composeContentWarningField);
    charactersLeft = findViewById(R.id.composeCharactersLeftView);
    tootButton = findViewById(R.id.composeTootButton);
    pickButton = findViewById(R.id.composeAddMediaButton);
    visibilityButton = findViewById(R.id.composeToggleVisibilityButton);
    contentWarningButton = findViewById(R.id.composeContentWarningButton);
    emojiButton = findViewById(R.id.composeEmojiButton);
    hideMediaToggle = findViewById(R.id.composeHideMediaButton);
    emojiView = findViewById(R.id.emojiView);
    emojiList = Collections.emptyList();

    saveTootHelper = new SaveTootHelper(database.tootDao(), this);

    // Setup the toolbar.
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp);
        ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint);
        actionBar.setHomeAsUpIndicator(closeIcon);
    }

    // setup the account image
    final AccountEntity activeAccount = accountManager.getActiveAccount();

    if (activeAccount != null) {
        ImageView composeAvatar = findViewById(R.id.composeAvatar);

        if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) {
            composeAvatar.setImageResource(R.drawable.avatar_default);
        } else {
            Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default)
                    .placeholder(R.drawable.avatar_default).into(composeAvatar);
        }

        composeAvatar.setContentDescription(
                getString(R.string.compose_active_account_description, activeAccount.getFullName()));

        mastodonApi.getInstance().enqueue(new Callback<Instance>() {
            @Override
            public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) {
                if (response.isSuccessful() && response.body().getMaxTootChars() != null) {
                    maximumTootCharacters = response.body().getMaxTootChars();
                    updateVisibleCharactersLeft();
                    cacheInstanceMetadata(activeAccount);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading instance data", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });

        mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() {
            @Override
            public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) {
                emojiList = response.body();
                setEmojiList(emojiList);
                cacheInstanceMetadata(activeAccount);
            }

            @Override
            public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading custom emojis", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });
    } else {
        // do not do anything when not logged in, activity will be finished in super.onCreate() anyway
        return;
    }

    composeOptionsView = findViewById(R.id.composeOptionsBottomSheet);
    composeOptionsView.setListener(this);

    composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView);
    composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

    addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet));

    emojiBehavior = BottomSheetBehavior.from(emojiView);

    emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false));

    enableButton(emojiButton, false, false);

    // Setup the interface buttons.
    tootButton.setOnClickListener(v -> onSendClicked());
    pickButton.setOnClickListener(v -> openPickDialog());
    visibilityButton.setOnClickListener(v -> showComposeOptions());
    contentWarningButton.setOnClickListener(v -> onContentWarningChanged());
    emojiButton.setOnClickListener(v -> showEmojis());
    hideMediaToggle.setOnClickListener(v -> toggleHideMedia());

    TextView actionPhotoTake = findViewById(R.id.action_photo_take);
    TextView actionPhotoPick = findViewById(R.id.action_photo_pick);

    int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary);

    Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor)
            .sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null,
            null);

    Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null,
            null);

    actionPhotoTake.setOnClickListener(v -> initiateCameraApp());
    actionPhotoPick.setOnClickListener(v -> onMediaPick());

    thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size);

    /* Initialise all the state, or restore it from a previous run, to determine a "starting"
     * state. */
    Status.Visibility startingVisibility = Status.Visibility.UNKNOWN;
    boolean startingHideText;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        startingVisibility = Status.Visibility
                .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum()));
        statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive");
        startingHideText = savedInstanceState.getBoolean("statusHideText");
        // Keep these until everything needed to put them in the queue is finished initializing.
        savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued");
        // These are for restoring an in-progress commit content operation.
        InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat
                .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo"));
        int previousFlags = savedInstanceState.getInt("commitContentFlags");
        if (previousInputContentInfo != null) {
            onCommitContentInternal(previousInputContentInfo, previousFlags);
        }
        photoUploadUri = savedInstanceState.getParcelable("photoUploadUri");
    } else {
        statusMarkSensitive = false;
        startingHideText = false;
        photoUploadUri = null;
    }

    /* If the composer is started up as a reply to another post, override the "starting" state
     * based on what the intent from the reply request passes. */
    Intent intent = getIntent();

    String[] mentionedUsernames = null;
    ArrayList<String> loadedDraftMediaUris = null;
    inReplyToId = null;
    if (intent != null) {

        if (startingVisibility == Status.Visibility.UNKNOWN) {
            Status.Visibility preferredVisibility = Status.Visibility.byString(
                    preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString()));
            Status.Visibility replyVisibility = Status.Visibility
                    .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum()));

            startingVisibility = Status.Visibility
                    .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum()));
        }

        inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA);

        mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA);

        String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA);
        if (contentWarning != null) {
            startingHideText = !contentWarning.isEmpty();
            if (startingHideText) {
                startingContentWarning = contentWarning;
            }
        }

        // If come from SavedTootActivity
        String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA);
        if (!TextUtils.isEmpty(savedTootText)) {
            startingText = savedTootText;
            textEditor.setText(savedTootText);
        }

        String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA);
        if (!TextUtils.isEmpty(savedJsonUrls)) {
            // try to redo a list of media
            loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() {
            }.getType());
        }

        int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0);
        if (savedTootUid != 0) {
            this.savedTootUid = savedTootUid;
        }

        if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) {
            replyTextView.setVisibility(View.VISIBLE);
            String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA);
            replyTextView.setText(getString(R.string.replying_to, username));
            Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down)
                    .sizeDp(12);

            ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary);
            TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                    arrowDownIcon, null);

            replyTextView.setOnClickListener(v -> {
                TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent());

                if (replyContentTextView.getVisibility() != View.VISIBLE) {
                    replyContentTextView.setVisibility(View.VISIBLE);
                    Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up)
                            .sizeDp(12);

                    ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary);
                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowUpIcon, null);
                } else {
                    replyContentTextView.setVisibility(View.GONE);

                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowDownIcon, null);
                }
            });
        }

        if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) {
            replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA));
        }
    }

    // After the starting state is finalised, the interface can be set to reflect this state.
    setStatusVisibility(startingVisibility);

    updateHideMediaToggle();
    updateVisibleCharactersLeft();

    // Setup the main text field.
    textEditor.setOnCommitContentListener(this);
    final int mentionColour = textEditor.getLinkTextColors().getDefaultColor();
    SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            SpanUtilsKt.highlightSpans(editable, mentionColour);
            updateVisibleCharactersLeft();
        }
    });

    textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this));
    textEditor.setTokenizer(new MentionTokenizer());

    // Add any mentions to the text field when a reply is first composed.
    if (mentionedUsernames != null) {
        StringBuilder builder = new StringBuilder();
        for (String name : mentionedUsernames) {
            builder.append('@');
            builder.append(name);
            builder.append(' ');
        }
        startingText = builder.toString();
        textEditor.setText(startingText);
        textEditor.setSelection(textEditor.length());
    }

    // work around Android platform bug -> https://issuetracker.google.com/issues/67102093
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
        textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // Initialise the content warning editor.
    contentWarningEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    showContentWarning(startingHideText);
    if (startingContentWarning != null) {
        contentWarningEditor.setText(startingContentWarning);
    }

    // Initialise the empty media queue state.
    waitForMediaLatch = new CountUpDownLatch();

    // These can only be added after everything affected by the media queue is initialized.
    if (!ListUtils.isEmpty(loadedDraftMediaUris)) {
        for (String uriString : loadedDraftMediaUris) {
            Uri uri = Uri.parse(uriString);
            long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
            pickMedia(uri, mediaSize);
        }
    } else if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize);
            addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage,
                    item.description);
        }
    } else if (intent != null && savedInstanceState == null) {
        /* Get incoming images being sent through a share action from another app. Only do this
         * when savedInstanceState is null, otherwise both the images from the intent and the
         * instance state will be re-queued. */
        String type = intent.getType();
        if (type != null) {
            if (type.startsWith("image/")) {
                List<Uri> uriList = new ArrayList<>();
                if (intent.getAction() != null) {
                    switch (intent.getAction()) {
                    case Intent.ACTION_SEND: {
                        Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                        if (uri != null) {
                            uriList.add(uri);
                        }
                        break;
                    }
                    case Intent.ACTION_SEND_MULTIPLE: {
                        ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                        if (list != null) {
                            for (Uri uri : list) {
                                if (uri != null) {
                                    uriList.add(uri);
                                }
                            }
                        }
                        break;
                    }
                    }
                }
                for (Uri uri : uriList) {
                    long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
                    pickMedia(uri, mediaSize);
                }
            } else if (type.equals("text/plain")) {
                String action = intent.getAction();
                if (action != null && action.equals(Intent.ACTION_SEND)) {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text != null) {
                        int start = Math.max(textEditor.getSelectionStart(), 0);
                        int end = Math.max(textEditor.getSelectionEnd(), 0);
                        int left = Math.min(start, end);
                        int right = Math.max(start, end);
                        textEditor.getText().replace(left, right, text, 0, text.length());
                    }
                }
            }
        }
    }

    textEditor.requestFocus();
}

From source file:com.android.launcher2.Launcher.java

boolean startActivity(View v, Intent intent, Object tag) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    try {/*w  w  w . ja v  a 2 s  .c om*/
        // Only launch using the new animation if the shortcut has not opted out (this is a
        // private contract between launcher and may be ignored in the future).
        boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
        if (useLaunchAnimation) {
            ActivityOptionsCompat opts = ActivityOptionsCompat.makeScaleUpAnimation(v, 0, 0,
                    v.getMeasuredWidth(), v.getMeasuredHeight());

            ActivityCompat.startActivity(this, intent, opts.toBundle());
        } else {
            startActivity(intent);
        }
        return true;
    } catch (SecurityException e) {
        Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Launcher does not have the permission to launch " + intent
                + ". Make sure to create a MAIN intent-filter for the corresponding activity "
                + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e);
    }
    return false;
}

From source file:com.ichi2.anki2.DeckPicker.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    mDontSaveOnStop = false;//from   www.  j ava  2  s .c  om
    if (resultCode == RESULT_MEDIA_EJECTED) {
        showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
        return;
    } else if (resultCode == RESULT_DB_ERROR) {
        handleDbError();
        return;
    }
    if (requestCode == SHOW_STUDYOPTIONS && resultCode == RESULT_OK) {
        loadCounts();
    } else if (requestCode == ADD_NOTE && resultCode != RESULT_CANCELED) {
        loadCounts();
    } else if (requestCode == BROWSE_CARDS
            && (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED)) {
        loadCounts();
    } else if (requestCode == ADD_CRAM_DECK) {
        // TODO: check, if ok has been clicked
        loadCounts();
    } else if (requestCode == REPORT_ERROR) {
        showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 4);
    } else if (requestCode == SHOW_INFO_UPGRADE_DECKS) {
        if (intent != null && intent.hasExtra(Info.TYPE_UPGRADE_STAGE)) {
            int type = intent.getIntExtra(Info.TYPE_UPGRADE_STAGE, Info.UPGRADE_SCREEN_BASIC1);
            if (type == Info.UPGRADE_CONTINUE) {
                showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 3);
            } else {
                showUpgradeScreen(true, type, !intent.hasExtra(Info.TYPE_ANIMATION_RIGHT));
            }
        } else {
            if (resultCode == RESULT_OK) {
                if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
                    mOpenCollectionDialog.dismiss();
                }
                if (AnkiDroidApp.colIsOpen()) {
                    AnkiDroidApp.closeCollection(true);
                }
                AnkiDroidApp.openCollection(AnkiDroidApp.getCollectionPath());
                loadCounts();
            } else {
                finishWithAnimation();
            }
        }
    } else if (requestCode == SHOW_INFO_WELCOME || requestCode == SHOW_INFO_NEW_VERSION) {
        if (resultCode == RESULT_OK) {
            showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()),
                    requestCode == SHOW_INFO_WELCOME ? 1 : 2);
        } else {
            finishWithAnimation();
        }
    } else if (requestCode == PREFERENCES_UPDATE) {
        String oldPath = mPrefDeckPath;
        SharedPreferences pref = restorePreferences();
        String newLanguage = pref.getString("language", "");
        if (!AnkiDroidApp.getLanguage().equals(newLanguage)) {
            AnkiDroidApp.setLanguage(newLanguage);
            mInvalidateMenu = true;
        }
        if (mNotMountedDialog != null && mNotMountedDialog.isShowing()
                && pref.getBoolean("internalMemory", false)) {
            showStartupScreensAndDialogs(pref, 0);
        } else if (!mPrefDeckPath.equals(oldPath)) {
            loadCollection();
        }
        // if (resultCode == StudyOptions.RESULT_RESTART) {
        // setResult(StudyOptions.RESULT_RESTART);
        // finishWithAnimation();
        // } else {
        // SharedPreferences preferences = PrefSettings.getSharedPrefs(getBaseContext());
        // BackupManager.initBackup();
        // if (!mPrefDeckPath.equals(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory())) ||
        // mPrefDeckOrder != Integer.parseInt(preferences.getString("deckOrder", "0"))) {
        // // populateDeckList(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory()));
        // }
        // }
    } else if (requestCode == REPORT_FEEDBACK && resultCode == RESULT_OK) {
    } else if (requestCode == LOG_IN_FOR_SYNC && resultCode == RESULT_OK) {
        sync();
    } else if (requestCode == LOG_IN_FOR_SHARED_DECK && resultCode == RESULT_OK) {
        addSharedDeck();
    } else if (requestCode == ADD_SHARED_DECKS) {
        if (intent != null) {
            mImportPath = intent.getStringExtra("importPath");
        }
        if (AnkiDroidApp.colIsOpen() && mImportPath != null) {
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, mImportAddListener,
                    new TaskData(AnkiDroidApp.getCol(), mImportPath, true));
            mImportPath = null;
        }
    } else if (requestCode == REQUEST_REVIEW) {
        Log.i(AnkiDroidApp.TAG, "Result code = " + resultCode);
        switch (resultCode) {
        default:
            // do not reload counts, if activity is created anew because it has been before destroyed by android
            loadCounts();
            break;
        case Reviewer.RESULT_NO_MORE_CARDS:
            mDontSaveOnStop = true;
            Intent i = new Intent();
            i.setClass(this, StudyOptionsActivity.class);
            i.putExtra("onlyFnsMsg", true);
            startActivityForResult(i, SHOW_STUDYOPTIONS);
            if (AnkiDroidApp.SDK_VERSION > 4) {
                ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
            }
            break;
        }

    }

    // workaround for hidden dialog on return
    BroadcastMessages.showDialog();
}

From source file:com.nit.vicky.DeckPicker.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    mDontSaveOnStop = false;/*from w  w  w  .  ja v a2s .c om*/
    if (resultCode == RESULT_MEDIA_EJECTED) {
        showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
        return;
    } else if (resultCode == RESULT_DB_ERROR) {
        handleDbError();
        return;
    }
    if (requestCode == SHOW_STUDYOPTIONS && resultCode == RESULT_OK) {
        loadCounts();
    } else if (requestCode == ADD_NOTE && resultCode != RESULT_CANCELED) {
        loadCounts();
        addNote();
    } else if (requestCode == BROWSE_CARDS
            && (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED)) {
        loadCounts();
    } else if (requestCode == ADD_CRAM_DECK) {
        // TODO: check, if ok has been clicked
        loadCounts();
    } else if (requestCode == REPORT_ERROR) {
        showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 4);
    } else if (requestCode == SHOW_INFO_UPGRADE_DECKS) {
        if (intent != null && intent.hasExtra(Info.TYPE_UPGRADE_STAGE)) {
            int type = intent.getIntExtra(Info.TYPE_UPGRADE_STAGE, Info.UPGRADE_SCREEN_BASIC1);
            if (type == Info.UPGRADE_CONTINUE) {
                showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 3);
            } else {
                showUpgradeScreen(true, type, !intent.hasExtra(Info.TYPE_ANIMATION_RIGHT));
            }
        } else {
            if (resultCode == RESULT_OK) {
                if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
                    mOpenCollectionDialog.dismiss();
                }
                if (AnkiDroidApp.colIsOpen()) {
                    AnkiDroidApp.closeCollection(true);
                }
                AnkiDroidApp.openCollection(AnkiDroidApp.getCollectionPath());
                loadCounts();
            } else {
                finishWithAnimation();
            }
        }
    } else if (requestCode == SHOW_INFO_WELCOME || requestCode == SHOW_INFO_NEW_VERSION) {
        if (resultCode == RESULT_OK) {
            showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()),
                    requestCode == SHOW_INFO_WELCOME ? 1 : 2);
        } else {
            finishWithAnimation();
        }
    } else if (requestCode == PREFERENCES_UPDATE) {
        String oldPath = mPrefDeckPath;
        SharedPreferences pref = restorePreferences();
        String newLanguage = pref.getString("language", "");
        if (AnkiDroidApp.setLanguage(newLanguage)) {
            mInvalidateMenu = true;
        }
        if (mNotMountedDialog != null && mNotMountedDialog.isShowing()
                && pref.getBoolean("internalMemory", false)) {
            showStartupScreensAndDialogs(pref, 0);
        } else if (!mPrefDeckPath.equals(oldPath)) {
            loadCollection();
        }
        // if (resultCode == StudyOptions.RESULT_RESTART) {
        // setResult(StudyOptions.RESULT_RESTART);
        // finishWithAnimation();
        // } else {
        // SharedPreferences preferences = PrefSettings.getSharedPrefs(getBaseContext());
        // BackupManager.initBackup();
        // if (!mPrefDeckPath.equals(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory())) ||
        // mPrefDeckOrder != Integer.parseInt(preferences.getString("deckOrder", "0"))) {
        // // populateDeckList(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory()));
        // }
        // }
    } else if (requestCode == REPORT_FEEDBACK && resultCode == RESULT_OK) {
    } else if (requestCode == LOG_IN_FOR_SYNC && resultCode == RESULT_OK) {
        sync();
    } else if (requestCode == LOG_IN_FOR_SHARED_DECK && resultCode == RESULT_OK) {
        addSharedDeck();
    } else if (requestCode == ADD_SHARED_DECKS) {
        if (intent != null) {
            mImportPath = intent.getStringExtra("importPath");
        }
        if (AnkiDroidApp.colIsOpen() && mImportPath != null) {
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, mImportAddListener,
                    new TaskData(AnkiDroidApp.getCol(), mImportPath, true));
            mImportPath = null;
        }
    } else if (requestCode == REQUEST_REVIEW) {
        // Log.i(AnkiDroidApp.TAG, "Result code = " + resultCode);
        switch (resultCode) {
        default:
            // do not reload counts, if activity is created anew because it has been before destroyed by android
            loadCounts();
            break;
        case Reviewer.RESULT_NO_MORE_CARDS:
            mDontSaveOnStop = true;
            Intent i = new Intent();
            i.setClass(this, StudyOptionsActivity.class);
            i.putExtra("onlyFnsMsg", true);
            startActivityForResult(i, SHOW_STUDYOPTIONS);
            if (AnkiDroidApp.SDK_VERSION > 4) {
                ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
            }
            break;
        }

    }

    // workaround for hidden dialog on return
    BroadcastMessages.showDialog();
}

From source file:com.hichinaschool.flashcards.anki.DeckPicker.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    mDontSaveOnStop = false;/*from   w ww.  j  av  a 2 s  .  co  m*/
    if (resultCode == RESULT_MEDIA_EJECTED) {
        showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
        return;
    } else if (resultCode == RESULT_DB_ERROR) {
        handleDbError();
        return;
    }
    if (requestCode == SHOW_STUDYOPTIONS && resultCode == RESULT_OK) {
        loadCounts();
    } else if (requestCode == ADD_NOTE && resultCode != RESULT_CANCELED) {
        loadCounts();
    } else if (requestCode == BROWSE_CARDS
            && (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED)) {
        loadCounts();
    } else if (requestCode == ADD_CRAM_DECK) {
        // TODO: check, if ok has been clicked
        loadCounts();
    } else if (requestCode == REPORT_ERROR) {
        showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 4);
    } else if (requestCode == SHOW_INFO_UPGRADE_DECKS) {
        if (intent != null && intent.hasExtra(Info.TYPE_UPGRADE_STAGE)) {
            int type = intent.getIntExtra(Info.TYPE_UPGRADE_STAGE, Info.UPGRADE_SCREEN_BASIC1);
            if (type == Info.UPGRADE_CONTINUE) {
                showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 3);
            } else {
                showUpgradeScreen(true, type, !intent.hasExtra(Info.TYPE_ANIMATION_RIGHT));
            }
        } else {
            if (resultCode == RESULT_OK) {
                if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
                    mOpenCollectionDialog.dismiss();
                }
                if (AnkiDroidApp.colIsOpen()) {
                    AnkiDroidApp.closeCollection(true);
                }
                AnkiDroidApp.openCollection(AnkiDroidApp.getCollectionPath());
                loadCounts();
            } else {
                finishWithAnimation();
            }
        }
    } else if (requestCode == SHOW_INFO_WELCOME || requestCode == SHOW_INFO_NEW_VERSION) {
        if (resultCode == RESULT_OK) {
            showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()),
                    requestCode == SHOW_INFO_WELCOME ? 1 : 2);
        } else {
            finishWithAnimation();
        }
    } else if (requestCode == PREFERENCES_UPDATE) {
        String oldPath = mPrefDeckPath;
        SharedPreferences pref = restorePreferences();
        String newLanguage = pref.getString("language", "");
        if (AnkiDroidApp.setLanguage(newLanguage)) {
            mInvalidateMenu = true;
        }
        if (mNotMountedDialog != null && mNotMountedDialog.isShowing()
                && pref.getBoolean("internalMemory", false)) {
            showStartupScreensAndDialogs(pref, 0);
        } else if (!mPrefDeckPath.equals(oldPath)) {
            loadCollection();
        }
        // if (resultCode == StudyOptions.RESULT_RESTART) {
        // setResult(StudyOptions.RESULT_RESTART);
        // finishWithAnimation();
        // } else {
        // SharedPreferences preferences = PrefSettings.getSharedPrefs(getBaseContext());
        // BackupManager.initBackup();
        // if (!mPrefDeckPath.equals(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory())) ||
        // mPrefDeckOrder != Integer.parseInt(preferences.getString("deckOrder", "0"))) {
        // // populateDeckList(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory()));
        // }
        // }
    } else if (requestCode == REPORT_FEEDBACK && resultCode == RESULT_OK) {
    } else if (requestCode == LOG_IN_FOR_SYNC && resultCode == RESULT_OK) {
        sync();
    } else if (requestCode == LOG_IN_FOR_SHARED_DECK && resultCode == RESULT_OK) {
        addSharedDeck();
    } else if (requestCode == ADD_SHARED_DECKS) {
        if (intent != null) {
            mImportPath = intent.getStringExtra("importPath");
        }
        if (AnkiDroidApp.colIsOpen() && mImportPath != null) {
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, mImportAddListener,
                    new TaskData(AnkiDroidApp.getCol(), mImportPath, true));
            mImportPath = null;
        }
    } else if (requestCode == REQUEST_REVIEW) {
        // Log.i(AnkiDroidApp.TAG, "Result code = " + resultCode);
        switch (resultCode) {
        default:
            // do not reload counts, if activity is created anew because it has been before destroyed by android
            loadCounts();
            break;
        case Reviewer.RESULT_NO_MORE_CARDS:
            mDontSaveOnStop = true;
            Intent i = new Intent();
            i.setClass(this, StudyOptionsActivity.class);
            i.putExtra("onlyFnsMsg", true);
            startActivityForResult(i, SHOW_STUDYOPTIONS);
            if (AnkiDroidApp.SDK_VERSION > 4) {
                ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
            }
            break;
        }

    }

    // workaround for hidden dialog on return
    BroadcastMessages.showDialog();
}

From source file:com.chen.mail.ui.AbstractActivityController.java

/**
 * Handle an intent to open the app. This method is called only when there is no saved state,
 * so we need to set state that wasn't set before. It is correct to change the viewmode here
 * since it has not been previously set.
 *
 * This method is called for a subset of the reasons mentioned in
 * {@link #onCreate(android.os.Bundle)}. Notably, this is called when launching the app from
 * notifications, widgets, and shortcuts.
 * @param intent intent passed to the activity.
 *//* w w w  .  j a v a  2  s.c om*/
private void handleIntent(Intent intent) {
    LogUtils.d(LOG_TAG, "IN AAC.handleIntent. action=%s", intent.getAction());
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
            setAccount(Account.newinstance(intent.getStringExtra(Utils.EXTRA_ACCOUNT)));
        }
        if (mAccount == null) {
            return;
        }
        final boolean isConversationMode = intent.hasExtra(Utils.EXTRA_CONVERSATION);

        if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
            Analytics.getInstance().setCustomDimension(Analytics.CD_INDEX_ACCOUNT_TYPE,
                    AnalyticsUtils.getAccountTypeForAccount(mAccount.getEmailAddress()));
            Analytics.getInstance().sendEvent("notification_click",
                    isConversationMode ? "conversation" : "conversation_list", null, 0);
        }

        if (isConversationMode && mViewMode.getMode() == ViewMode.UNKNOWN) {
            mViewMode.enterConversationMode();
        } else {
            mViewMode.enterConversationListMode();
        }
        // Put the folder and conversation, and ask the loader to create this folder.
        final Bundle args = new Bundle();

        final Uri folderUri;
        if (intent.hasExtra(Utils.EXTRA_FOLDER_URI)) {
            folderUri = (Uri) intent.getParcelableExtra(Utils.EXTRA_FOLDER_URI);
        } else if (intent.hasExtra(Utils.EXTRA_FOLDER)) {
            final Folder folder = Folder.fromString(intent.getStringExtra(Utils.EXTRA_FOLDER));
            folderUri = folder.folderUri.fullUri;
        } else {
            final Bundle extras = intent.getExtras();
            LogUtils.d(LOG_TAG, "Couldn't find a folder URI in the extras: %s",
                    extras == null ? "null" : extras.toString());
            folderUri = mAccount.settings.defaultInbox;
        }

        args.putParcelable(Utils.EXTRA_FOLDER_URI, folderUri);
        args.putParcelable(Utils.EXTRA_CONVERSATION, intent.getParcelableExtra(Utils.EXTRA_CONVERSATION));
        restartOptionalLoader(LOADER_FIRST_FOLDER, mFolderCallbacks, args);
    } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
            mHaveSearchResults = false;
            // Save this search query for future suggestions.
            final String query = intent.getStringExtra(SearchManager.QUERY);
            final String authority = mContext.getString(R.string.suggestions_authority);
            final SearchRecentSuggestions suggestions = new SearchRecentSuggestions(mContext, authority,
                    SuggestionsProvider.MODE);
            suggestions.saveRecentQuery(query, null);
            setAccount((Account) intent.getParcelableExtra(Utils.EXTRA_ACCOUNT));
            fetchSearchFolder(intent);
            if (shouldEnterSearchConvMode()) {
                mViewMode.enterSearchResultsConversationMode();
            } else {
                mViewMode.enterSearchResultsListMode();
            }
        } else {
            LogUtils.e(LOG_TAG, "Missing account extra from search intent.  Finishing");
            mActivity.finish();
        }
    }
    if (mAccount != null) {
        restartOptionalLoader(LOADER_ACCOUNT_UPDATE_CURSOR, mAccountCallbacks, Bundle.EMPTY);
    }
}

From source file:com.android.mail.ui.AbstractActivityController.java

/**
 * Handle an intent to open the app. This method is called only when there is no saved state,
 * so we need to set state that wasn't set before. It is correct to change the viewmode here
 * since it has not been previously set.
 *
 * This method is called for a subset of the reasons mentioned in
 * {@link #onCreate(android.os.Bundle)}. Notably, this is called when launching the app from
 * notifications, widgets, and shortcuts.
 * @param intent intent passed to the activity.
 *//* www.j  a va  2  s  .c  om*/
private void handleIntent(Intent intent) {
    LogUtils.d(LOG_TAG, "IN AAC.handleIntent. action=%s", intent.getAction());
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
            setAccount(Account.newInstance(intent.getStringExtra(Utils.EXTRA_ACCOUNT)));
        }
        if (mAccount == null) {
            return;
        }
        final boolean isConversationMode = intent.hasExtra(Utils.EXTRA_CONVERSATION);

        if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
            Analytics.getInstance().setEmail(mAccount.getEmailAddress(), mAccount.getType());
            Analytics.getInstance().sendEvent("notification_click",
                    isConversationMode ? "conversation" : "conversation_list", null, 0);
        }

        if (isConversationMode && mViewMode.getMode() == ViewMode.UNKNOWN) {
            mViewMode.enterConversationMode();
        } else {
            mViewMode.enterConversationListMode();
        }
        // Put the folder and conversation, and ask the loader to create this folder.
        final Bundle args = new Bundle();

        final Uri folderUri;
        if (intent.hasExtra(Utils.EXTRA_FOLDER_URI)) {
            folderUri = intent.getParcelableExtra(Utils.EXTRA_FOLDER_URI);
        } else if (intent.hasExtra(Utils.EXTRA_FOLDER)) {
            final Folder folder = Folder.fromString(intent.getStringExtra(Utils.EXTRA_FOLDER));
            folderUri = folder.folderUri.fullUri;
        } else {
            final Bundle extras = intent.getExtras();
            LogUtils.d(LOG_TAG, "Couldn't find a folder URI in the extras: %s",
                    extras == null ? "null" : extras.toString());
            folderUri = mAccount.settings.defaultInbox;
        }

        // Check if we should load all conversations instead of using
        // the default behavior which loads an initial subset.
        mIgnoreInitialConversationLimit = intent.getBooleanExtra(Utils.EXTRA_IGNORE_INITIAL_CONVERSATION_LIMIT,
                false);

        args.putParcelable(Utils.EXTRA_FOLDER_URI, folderUri);
        args.putParcelable(Utils.EXTRA_CONVERSATION, intent.getParcelableExtra(Utils.EXTRA_CONVERSATION));
        restartOptionalLoader(LOADER_FIRST_FOLDER, mFolderCallbacks, args);
    } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
            mHaveSearchResults = false;
            // Save this search query for future suggestions
            final String query = intent.getStringExtra(SearchManager.QUERY);
            mSearchViewController.saveRecentQuery(query);
            setAccount((Account) intent.getParcelableExtra(Utils.EXTRA_ACCOUNT));
            fetchSearchFolder(intent);
            if (shouldEnterSearchConvMode()) {
                mViewMode.enterSearchResultsConversationMode();
            } else {
                mViewMode.enterSearchResultsListMode();
            }
        } else {
            LogUtils.e(LOG_TAG, "Missing account extra from search intent.  Finishing");
            mActivity.finish();
        }
    }
    if (mAccount != null) {
        restartOptionalLoader(LOADER_ACCOUNT_UPDATE_CURSOR, mAccountCallbacks, Bundle.EMPTY);
    }
}

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

private Account obtainAccount(Intent intent) {
    Account account = null;//w w w.j a  va2s. c  om
    Object accountExtra = null;
    if (intent != null && intent.getExtras() != null) {
        accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
        if (accountExtra instanceof Account) {
            return (Account) accountExtra;
        } else if (accountExtra instanceof String) {
            // This is the Account attached to the widget compose intent.
            account = Account.newInstance((String) accountExtra);
            if (account != null) {
                return account;
            }
        }
        accountExtra = intent.hasExtra(Utils.EXTRA_ACCOUNT) ? intent.getStringExtra(Utils.EXTRA_ACCOUNT)
                : intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
    }

    MailAppProvider provider = MailAppProvider.getInstance();
    String lastAccountUri = provider.getLastSentFromAccount();
    if (TextUtils.isEmpty(lastAccountUri)) {
        lastAccountUri = provider.getLastViewedAccount();
    }
    if (!TextUtils.isEmpty(lastAccountUri)) {
        accountExtra = Uri.parse(lastAccountUri);
    }

    if (mAccounts != null && mAccounts.length > 0) {
        if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
            // For backwards compatibility, we need to check account
            // names.
            for (Account a : mAccounts) {
                if (a.getEmailAddress().equals(accountExtra)) {
                    account = a;
                }
            }
        } else if (accountExtra instanceof Uri) {
            // The uri of the last viewed account is what is stored in
            // the current code base.
            for (Account a : mAccounts) {
                if (a.uri.equals(accountExtra)) {
                    account = a;
                }
            }
        }
        if (account == null) {
            account = mAccounts[0];
        }
    }
    return account;
}