Example usage for android.content Intent getParcelableExtra

List of usage examples for android.content Intent getParcelableExtra

Introduction

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

Prototype

public <T extends Parcelable> T getParcelableExtra(String name) 

Source Link

Document

Retrieve extended data from the intent.

Usage

From source file:com.android.mms.ui.ComposeMessageActivity.java

private boolean handleForwardedMessage() {
    Intent intent = getIntent();

    // If this is a forwarded message, it will have an Intent extra
    // indicating so.  If not, bail out.
    if (!mForwardMessageMode) {
        if (mConversation != null) {
            mConversation.setHasMmsForward(false);
        }// w  w w .  j  ava2 s.  co m
        return false;
    }

    if (mConversation != null) {
        mConversation.setHasMmsForward(true);
        String recipientNumber = intent.getStringExtra("msg_recipient");
        mConversation.setForwardRecipientNumber(recipientNumber);
    }
    Uri uri = intent.getParcelableExtra("msg_uri");

    if (Log.isLoggable(LogTag.APP, Log.DEBUG)) {
        log("" + uri);
    }

    if (uri != null) {
        mWorkingMessage = WorkingMessage.load(this, uri);
        mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
    } else {
        mWorkingMessage.setText(intent.getStringExtra("sms_body"));
    }

    // let's clear the message thread for forwarded messages
    mMsgListAdapter.changeCursor(null);

    return true;
}

From source file:it.feio.android.omninotes.DetailFragment.java

private void handleIntents() {
    Intent i = mainActivity.getIntent();

    if (IntentChecker.checkAction(i, Constants.ACTION_MERGE)) {
        noteOriginal = new Note();
        note = new Note(noteOriginal);
        noteTmp = getArguments().getParcelable(Constants.INTENT_NOTE);
        if (i.getStringArrayListExtra("merged_notes") != null) {
            mergedNotesIds = i.getStringArrayListExtra("merged_notes");
        }//from  w  w  w . j  a  v  a  2  s.c  om
    }

    // Action called from home shortcut
    if (IntentChecker.checkAction(i, Constants.ACTION_SHORTCUT, Constants.ACTION_NOTIFICATION_CLICK)) {
        afterSavedReturnsToList = false;
        noteOriginal = DbHelper.getInstance().getNote(i.getLongExtra(Constants.INTENT_KEY, 0));
        // Checks if the note pointed from the shortcut has been deleted
        try {
            note = new Note(noteOriginal);
            noteTmp = new Note(noteOriginal);
        } catch (NullPointerException e) {
            mainActivity.showToast(getText(R.string.shortcut_note_deleted), Toast.LENGTH_LONG);
            mainActivity.finish();
        }
    }

    // Check if is launched from a widget
    if (IntentChecker.checkAction(i, Constants.ACTION_WIDGET, Constants.ACTION_TAKE_PHOTO)) {

        afterSavedReturnsToList = false;
        showKeyboard = true;

        //  with tags to set tag
        if (i.hasExtra(Constants.INTENT_WIDGET)) {
            String widgetId = i.getExtras().get(Constants.INTENT_WIDGET).toString();
            if (widgetId != null) {
                String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, "");
                String categoryId = TextHelper.checkIntentCategory(sqlCondition);
                if (categoryId != null) {
                    Category category;
                    try {
                        category = DbHelper.getInstance().getCategory(Long.parseLong(categoryId));
                        noteTmp = new Note();
                        noteTmp.setCategory(category);
                    } catch (NumberFormatException e) {
                        Log.e(Constants.TAG, "Category with not-numeric value!", e);
                    }
                }
            }
        }

        // Sub-action is to take a photo
        if (IntentChecker.checkAction(i, Constants.ACTION_TAKE_PHOTO)) {
            takePhoto();
        }
    }

    /**
     * Handles third party apps requests of sharing
     */
    if (IntentChecker.checkAction(i, Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE,
            Constants.INTENT_GOOGLE_NOW) && i.getType() != null) {

        afterSavedReturnsToList = false;

        if (noteTmp == null)
            noteTmp = new Note();

        // Text title
        String title = i.getStringExtra(Intent.EXTRA_SUBJECT);
        if (title != null) {
            noteTmp.setTitle(title);
        }

        // Text content
        String content = i.getStringExtra(Intent.EXTRA_TEXT);
        if (content != null) {
            noteTmp.setContent(content);
        }

        // Single attachment data
        Uri uri = i.getParcelableExtra(Intent.EXTRA_STREAM);
        // Due to the fact that Google Now passes intent as text but with
        // audio recording attached the case must be handled in specific way
        if (uri != null && !Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) {
            String name = FileHelper.getNameFromUri(mainActivity, uri);
            AttachmentTask task = new AttachmentTask(this, uri, name, this);
            task.execute();
        }

        // Multiple attachment data
        ArrayList<Uri> uris = i.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        if (uris != null) {
            for (Uri uriSingle : uris) {
                String name = FileHelper.getNameFromUri(mainActivity, uriSingle);
                AttachmentTask task = new AttachmentTask(this, uriSingle, name, this);
                task.execute();
            }
        }

        //         i.setAction(null);
    }

    if (IntentChecker.checkAction(i, Intent.ACTION_MAIN, Constants.ACTION_WIDGET_SHOW_LIST)) {
        showKeyboard = true;
    }

}

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

private void finishCreate() {
    final Bundle savedState = mInnerSavedState;
    findViews();//from   w w  w.j a  v  a2s .  com
    final Intent intent = getIntent();
    final Message message;
    final ArrayList<AttachmentPreview> previews;
    mShowQuotedText = false;
    final CharSequence quotedText;
    int action;
    // Check for any of the possibly supplied accounts.;
    final Account account;
    if (hadSavedInstanceStateMessage(savedState)) {
        action = savedState.getInt(EXTRA_ACTION, COMPOSE);
        account = savedState.getParcelable(Utils.EXTRA_ACCOUNT);
        message = savedState.getParcelable(EXTRA_MESSAGE);

        previews = savedState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
        mRefMessage = savedState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
        quotedText = savedState.getCharSequence(EXTRA_QUOTED_TEXT);

        mExtraValues = savedState.getParcelable(EXTRA_VALUES);

        // Get the draft id from the request id if there is one.
        if (savedState.containsKey(EXTRA_REQUEST_ID)) {
            final int requestId = savedState.getInt(EXTRA_REQUEST_ID);
            if (sRequestMessageIdMap.containsKey(requestId)) {
                synchronized (mDraftLock) {
                    mDraftId = sRequestMessageIdMap.get(requestId);
                }
            }
        }
    } else {
        account = obtainAccount(intent);
        action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
        // Initialize the message from the message in the intent
        message = intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
        previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
        mRefMessage = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
        mRefMessageUri = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
        quotedText = null;

        if (Analytics.isLoggable()) {
            if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
                Analytics.getInstance().sendEvent("notification_action", "compose", getActionString(action), 0);
            }
        }
    }
    mAttachmentsView.setAttachmentPreviews(previews);

    setAccount(account);
    if (mAccount == null) {
        return;
    }

    initRecipients();

    // Clear the notification and mark the conversation as seen, if necessary
    final Folder notificationFolder = intent.getParcelableExtra(EXTRA_NOTIFICATION_FOLDER);

    if (notificationFolder != null) {
        final Uri conversationUri = intent.getParcelableExtra(EXTRA_NOTIFICATION_CONVERSATION);
        Intent actionIntent;
        if (conversationUri != null) {
            actionIntent = new Intent(MailIntentService.ACTION_RESEND_NOTIFICATIONS_WEAR);
            actionIntent.putExtra(Utils.EXTRA_CONVERSATION, conversationUri);
        } else {
            actionIntent = new Intent(MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
            actionIntent.setData(Utils.appendVersionQueryParameter(this, notificationFolder.folderUri.fullUri));
        }
        actionIntent.setPackage(getPackageName());
        actionIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
        actionIntent.putExtra(Utils.EXTRA_FOLDER, notificationFolder);

        startService(actionIntent);
    }

    if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
        mLaunchedFromEmail = true;
    } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
        final Uri dataUri = intent.getData();
        if (dataUri != null) {
            final String dataScheme = intent.getData().getScheme();
            final String accountScheme = mAccount.composeIntentUri.getScheme();
            mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
        }
    }

    if (mRefMessageUri != null) {
        mShowQuotedText = true;
        mComposeMode = action;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            String wearReply = null;
            if (remoteInput != null) {
                LogUtils.d(LOG_TAG, "Got remote input from new api");
                CharSequence input = remoteInput.getCharSequence(NotificationActionUtils.WEAR_REPLY_INPUT);
                if (input != null) {
                    wearReply = input.toString();
                }
            } else {
                // TODO: remove after legacy code has been removed.
                LogUtils.d(LOG_TAG, "No remote input from new api, falling back to compatibility mode");
                ClipData clipData = intent.getClipData();
                if (clipData != null && LEGACY_WEAR_EXTRA.equals(clipData.getDescription().getLabel())) {
                    Bundle extras = clipData.getItemAt(0).getIntent().getExtras();
                    if (extras != null) {
                        wearReply = extras.getString(NotificationActionUtils.WEAR_REPLY_INPUT);
                    }
                }
            }

            if (!TextUtils.isEmpty(wearReply)) {
                createWearReplyTask(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, mComposeMode,
                        wearReply).execute();
                finish();
                return;
            } else {
                LogUtils.w(LOG_TAG, "remote input string is null");
            }
        }

        getLoaderManager().initLoader(INIT_DRAFT_USING_REFERENCE_MESSAGE, null, this);
        return;
    } else if (message != null && action != EDIT_DRAFT) {
        initFromDraftMessage(message);
        initQuotedTextFromRefMessage(mRefMessage, action);
        mShowQuotedText = message.appendRefMessageContent;
        // if we should be showing quoted text but mRefMessage is null
        // and we have some quotedText, display that
        if (mShowQuotedText && mRefMessage == null) {
            if (quotedText != null) {
                initQuotedText(quotedText, false /* shouldQuoteText */);
            } else if (mExtraValues != null) {
                initExtraValues(mExtraValues);
                return;
            }
        }
    } else if (action == EDIT_DRAFT) {
        if (message == null) {
            throw new IllegalStateException("Message must not be null to edit draft");
        }
        initFromDraftMessage(message);
        // Update the action to the draft type of the previous draft
        switch (message.draftType) {
        case UIProvider.DraftType.REPLY:
            action = REPLY;
            break;
        case UIProvider.DraftType.REPLY_ALL:
            action = REPLY_ALL;
            break;
        case UIProvider.DraftType.FORWARD:
            action = FORWARD;
            break;
        case UIProvider.DraftType.COMPOSE:
        default:
            action = COMPOSE;
            break;
        }
        LogUtils.d(LOG_TAG, "Previous draft had action type: %d", action);

        mShowQuotedText = message.appendRefMessageContent;
        if (message.refMessageUri != null) {
            // If we're editing an existing draft that was in reference to an existing message,
            // still need to load that original message since we might need to refer to the
            // original sender and recipients if user switches "reply <-> reply-all".
            mRefMessageUri = message.refMessageUri;
            mComposeMode = action;
            getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
            return;
        }
    } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
        if (mRefMessage != null) {
            initFromRefMessage(action);
            mShowQuotedText = true;
        }
    } else {
        if (initFromExtras(intent)) {
            return;
        }
    }

    mComposeMode = action;
    finishSetup(action, intent, savedState);
}

From source file:com.dycody.android.idealnote.DetailFragment.java

private void handleIntents() {
    Intent i = mainActivity.getIntent();

    if (IntentChecker.checkAction(i, Constants.ACTION_MERGE)) {
        noteOriginal = new Note();
        note = new Note(noteOriginal);
        noteTmp = getArguments().getParcelable(Constants.INTENT_NOTE);
        if (i.getStringArrayListExtra("merged_notes") != null) {
            mergedNotesIds = i.getStringArrayListExtra("merged_notes");
        }/*from  www  . ja v  a  2 s.co m*/
    }

    // Action called from home shortcut
    if (IntentChecker.checkAction(i, Constants.ACTION_SHORTCUT, Constants.ACTION_NOTIFICATION_CLICK)) {
        afterSavedReturnsToList = false;
        noteOriginal = DbHelper.getInstance().getNote(i.getLongExtra(Constants.INTENT_KEY, 0));
        // Checks if the note pointed from the shortcut has been deleted
        try {
            note = new Note(noteOriginal);
            noteTmp = new Note(noteOriginal);
        } catch (NullPointerException e) {
            mainActivity.showToast(getText(R.string.shortcut_note_deleted), Toast.LENGTH_LONG);
            mainActivity.finish();
        }
    }

    // Check if is launched from a widget
    if (IntentChecker.checkAction(i, Constants.ACTION_WIDGET, Constants.ACTION_TAKE_PHOTO)) {

        afterSavedReturnsToList = false;
        showKeyboard = true;

        //  with tags to set tag
        if (i.hasExtra(Constants.INTENT_WIDGET)) {
            String widgetId = i.getExtras().get(Constants.INTENT_WIDGET).toString();
            if (widgetId != null) {
                String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, "");
                String categoryId = TextHelper.checkIntentCategory(sqlCondition);
                if (categoryId != null) {
                    Category category;
                    try {
                        category = DbHelper.getInstance().getCategory(Long.parseLong(categoryId));
                        noteTmp = new Note();
                        noteTmp.setCategory(category);
                    } catch (NumberFormatException e) {
                        Log.e(Constants.TAG, "Category with not-numeric value!", e);
                    }
                }
            }
        }

        // Sub-action is to take a photo
        if (IntentChecker.checkAction(i, Constants.ACTION_TAKE_PHOTO)) {
            takePhoto();
        }
    }

    /**
     * Handles third party apps requests of sharing
     */
    if (IntentChecker.checkAction(i, Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE,
            Constants.INTENT_GOOGLE_NOW) && i.getType() != null) {

        afterSavedReturnsToList = false;

        if (noteTmp == null)
            noteTmp = new Note();

        // Text title
        String title = i.getStringExtra(Intent.EXTRA_SUBJECT);
        if (title != null) {
            noteTmp.setTitle(title);
        }

        // Text content
        String content = i.getStringExtra(Intent.EXTRA_TEXT);
        if (content != null) {
            noteTmp.setContent(content);
        }

        // Single attachment data
        Uri uri = i.getParcelableExtra(Intent.EXTRA_STREAM);
        // Due to the fact that Google Now passes intent as text but with
        // audio recording attached the case must be handled in specific way
        if (uri != null && !Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) {
            String name = FileHelper.getNameFromUri(mainActivity, uri);
            new AttachmentTask(this, uri, name, this).execute();
        }

        // Multiple attachment data
        ArrayList<Uri> uris = i.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        if (uris != null) {
            for (Uri uriSingle : uris) {
                String name = FileHelper.getNameFromUri(mainActivity, uriSingle);
                new AttachmentTask(this, uriSingle, name, this).execute();
            }
        }
    }

    if (IntentChecker.checkAction(i, Intent.ACTION_MAIN, Constants.ACTION_WIDGET_SHOW_LIST,
            Constants.ACTION_SHORTCUT_WIDGET, Constants.ACTION_WIDGET)) {
        showKeyboard = true;
    }

    i.setAction(null);
}

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.
 *///ww w.  j  a v a  2 s  .  com
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.
 *///  w w  w.  j a v a2s  .  com
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.cognizant.trumobi.PersonaLauncher.java

private void completeEditShirtcut(Intent data) {
    if (!data.hasExtra(PersonaCustomShirtcutActivity.EXTRA_APPLICATIONINFO))
        return;//  w  ww  .  ja  va2 s  .c o m
    long appInfoId = data.getLongExtra(PersonaCustomShirtcutActivity.EXTRA_APPLICATIONINFO, 0);
    PersonaApplicationInfo info = PersonaLauncherModel.loadApplicationInfoById(this, appInfoId);
    if (info != null) {
        Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);

        Drawable icon = null;
        boolean customIcon = false;
        ShortcutIconResource iconResource = null;

        if (bitmap != null) {
            icon = new PersonaFastBitmapDrawable(PersonaUtilities.createBitmapThumbnail(bitmap, this));
            customIcon = true;
        } else {
            Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
            if (extra != null && extra instanceof ShortcutIconResource) {
                try {
                    iconResource = (ShortcutIconResource) extra;
                    final PackageManager packageManager = getPackageManager();
                    Resources resources = packageManager.getResourcesForApplication(iconResource.packageName);
                    final int id = resources.getIdentifier(iconResource.resourceName, null, null);
                    icon = resources.getDrawable(id);
                } catch (Exception e) {
                    PersonaLog.w(LOG_TAG, "Could not load shortcut icon: " + extra);
                }
            }
        }

        if (icon != null) {
            info.icon = icon;
            info.customIcon = customIcon;
            info.iconResource = iconResource;
        }
        info.itemType = PersonaLauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
        info.title = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
        info.intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
        PersonaLauncherModel.updateItemInDatabase(this, info);

        if (info.container == PersonaLauncherSettings.Favorites.CONTAINER_MAB)
            mHandleView.UpdateLaunchInfo(info);
        else if (info.container == PersonaLauncherSettings.Favorites.CONTAINER_LAB)
            mLAB.UpdateLaunchInfo(info);
        else if (info.container == PersonaLauncherSettings.Favorites.CONTAINER_LAB2)
            mLAB2.UpdateLaunchInfo(info);
        else if (info.container == PersonaLauncherSettings.Favorites.CONTAINER_RAB)
            mRAB.UpdateLaunchInfo(info);
        else if (info.container == PersonaLauncherSettings.Favorites.CONTAINER_RAB2)
            mRAB2.UpdateLaunchInfo(info);

        mWorkspace.updateShortcutFromApplicationInfo(info);
    }
}

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

/**
 * The mail activity calls other activities for two specific reasons:
 * <ul>/*  w  w w  .j a  v  a  2 s .c  om*/
 *     <li>To add an account. And receives the result {@link #ADD_ACCOUNT_REQUEST_CODE}</li>
 *     <li>To update the password on a current account. The result {@link
 *     #REAUTHENTICATE_REQUEST_CODE} is received.</li>
 * </ul>
 * @param requestCode
 * @param resultCode
 * @param data
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case ADD_ACCOUNT_REQUEST_CODE:
        // We were waiting for the user to create an account
        if (resultCode == Activity.RESULT_OK) {
            // restart the loader to get the updated list of accounts
            mActivity.getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, Bundle.EMPTY, mAccountCallbacks);
        } else {
            // The user failed to create an account, just exit the app
            mActivity.finish();
        }
        break;
    case REAUTHENTICATE_REQUEST_CODE:
        if (resultCode == Activity.RESULT_OK) {
            // The user successfully authenticated, attempt to refresh the list
            final Uri refreshUri = mFolder != null ? mFolder.refreshUri : null;
            if (refreshUri != null) {
                startAsyncRefreshTask(refreshUri);
            }
        }
        break;
    case CHANGE_NAVIGATION_REQUEST_CODE:
        if (ViewMode.isSearchMode(mViewMode.getMode())) {
            mActivity.setResult(resultCode, data);
            mActivity.finish();
        } else if (resultCode == Activity.RESULT_OK && data != null) {
            // We have have received a result that indicates we need to navigate to a
            // different folder or account. This happens if someone navigates using the
            // drawer on the search results activity.
            final Folder folder = data.getParcelableExtra(EXTRA_FOLDER);
            final Account account = data.getParcelableExtra(EXTRA_ACCOUNT);
            if (folder != null) {
                onFolderSelected(folder);
                mViewMode.enterConversationListMode();
            } else if (account != null) {
                switchToDefaultInboxOrChangeAccount(account);
                mViewMode.enterConversationListMode();
            }
        }
        break;
    case VOICE_SEARCH_REQUEST_CODE:
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (!matches.isEmpty()) {
                // not sure how dependable the API is, but it's all we have.
                // take the top choice.
                mSearchViewController.onSearchPerformed(matches.get(0));
            }
        }
        break;
    }
}

From source file:com.theultimatelabs.scale.ScaleActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scale);//from www.j  a  v  a2 s .  com

    Log.v(TAG, "onCreate");

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    mSettings = getSharedPreferences(PREFS, 0);

    mUnitsText = mSettings.getString("unitsText", "grams");
    mUnitsRatio = mSettings.getFloat("unitsRatio", (float) 1.0);

    mTts = new TextToSpeech(this, this);

    mUnitsView = (TextView) findViewById(R.id.text_unit);
    mUnitsView.setText(mUnitsText);

    findViewById(R.id.text_unit).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            while (mTts.isSpeaking())
                ;
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say Units");
            startActivityForResult(intent, 0);

            if (adView != null) {
                adView.loadAd(new AdRequest());
            }

        }
    });

    mWeightTextView = (TextView) findViewById(R.id.text_weight);
    mWeightTextView.setText("00.00");
    /*
     * TextPaint weightTextPaint = mWeightTextView.getPaint(); CharSequence
     * weightText = mWeightTextView.getText(); while (weightText !=
     * TextUtils.ellipsize(weightText, weightTextPaint,
     * getWindowManager().getDefaultDisplay
     * ().getWidth()*2/3,TextUtils.TruncateAt.END)) {
     * weightTextPaint.setTextSize(weightTextPaint.getTextSize() - 1); }
     */

    mWeightTextView.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Zero'd", Toast.LENGTH_LONG).show();
            mZeroGrams = mWeightGrams;
            if (adView != null) {
                adView.loadAd(new AdRequest());
            }
        }
    });
    mWeightTextView.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            mZeroGrams = 0;
            Toast.makeText(getApplicationContext(), "Reset", Toast.LENGTH_LONG).show();
            if (adView != null) {
                adView.loadAd(new AdRequest());
            }
            return true;
        }
    });

    disableAdsText = (TextView) findViewById((R.id.text_disableAds));
    disableAdsText.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            new AlertDialog.Builder(ScaleActivity.this).setTitle("Keep Software Free and Open Source")
                    .setMessage("Ads help support further development, but they are OPTIONAL."
                            + " If you choose to disable ads, please consider donating. All dontations"
                            + " go towards purchasing hardware for open source development. "
                            + "Disabling ads or donating will not change the features availble in this app."
                            + " Thank you. rob@theultimatelabs.com")
                    .setPositiveButton("Disable Ads", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            adLayout.removeAllViews();
                            adView.removeAllViews();
                            disableAdsText.setVisibility(View.INVISIBLE);
                            mSettings.edit().putBoolean("ads", false).commit();
                            adView = null;
                        }
                    }).setCancelable(true).setNegativeButton("Keep Ads", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).setNeutralButton("Disable Ads + Donate", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            adLayout.removeAllViews();
                            adView.removeAllViews();
                            disableAdsText.setVisibility(View.INVISIBLE);
                            mSettings.edit().putBoolean("ads", false).commit();
                            adView = null;
                            startActivity(new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("http://blog.theultimatelabs.com/p/donate.html")));
                        }
                    }).show();
        }
    });

    TextView aboutText = (TextView) findViewById((R.id.text_about));
    aboutText.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(getApplicationContext(), AboutActivity.class));
        }
    });

    /*
     * .setMessage() new AlertDialog.Builder(this) .setMessage(mymessage)
     * .setTitle(title) .setCancelable(true)
     * .setNeutralButton(android.R.string.cancel, new
     * DialogInterface.OnClickListener() { public void
     * onClick(DialogInterface dialog, int whichButton){} }) .show(); }}
     */
    // /

    mDensitiesJson = loadJsonResource(R.raw.densities);
    mVolumesJson = loadJsonResource(R.raw.volumes);
    mWeightsJson = loadJsonResource(R.raw.weights);

    // Initiate a generic request to load it with an ad
    if (mSettings.getBoolean("ads", true)) {
        // Create the adViewj
        adView = new AdView(this, AdSize.SMART_BANNER, "a15089dfb39c5a8");

        // Log.w(TAG, new Integer(R.id.layout_ads).toString());
        adLayout = (LinearLayout) findViewById(R.id.layout_ads);

        // Add the adView to it
        adLayout.addView(adView, 0);
        disableAdsText.setVisibility(View.VISIBLE);
    } else {
        disableAdsText.setVisibility(View.INVISIBLE);
        adView = null;
    }

    Intent intent = getIntent();
    mDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

    findScale();

}

From source file:com.fa.mastodon.activity.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compose);
    ButterKnife.bind(this);

    // Setup the toolbar.
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from  ww w.jav  a  2  s  . c o  m
    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 interface buttons.
    floatingBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSendClicked();
        }
    });
    pickBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onMediaPick();
        }
    });
    takeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiateCameraApp();
        }
    });
    nsfwBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleNsfw();
        }
    });
    visibilityBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showComposeOptions();
        }
    });

    /* Initialise all the state, or restore it from a previous run, to determine a "starting"
     * state. */
    SharedPreferences preferences = getPrivatePreferences();

    String startingVisibility;
    boolean startingHideText;
    String startingContentWarning = null;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        showMarkSensitive = savedInstanceState.getBoolean("showMarkSensitive");
        startingVisibility = savedInstanceState.getString("statusVisibility");
        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);
        }
    } else {
        showMarkSensitive = false;
        startingVisibility = preferences.getString("rememberedVisibility", "public");
        statusMarkSensitive = false;
        startingHideText = false;
    }

    /* 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;
    inReplyToId = null;
    if (intent != null) {
        inReplyToId = intent.getStringExtra("in_reply_to_id");
        String replyVisibility = intent.getStringExtra("reply_visibility");

        if (replyVisibility != null && startingVisibility != null) {
            // Lowest possible visibility setting in response
            if (startingVisibility.equals("private") || replyVisibility.equals("private")) {
                startingVisibility = "private";
            } else if (startingVisibility.equals("unlisted") || replyVisibility.equals("unlisted")) {
                startingVisibility = "unlisted";
            } else {
                startingVisibility = replyVisibility;
            }
        }

        mentionedUsernames = intent.getStringArrayExtra("mentioned_usernames");

        if (inReplyToId != null) {
            startingHideText = !intent.getStringExtra("content_warning").equals("");
            if (startingHideText) {
                startingContentWarning = intent.getStringExtra("content_warning");
            }
        }
    }

    /* If the currently logged in account is locked, its posts should default to private. This
     * should override even the reply settings, so this must be done after those are set up. */
    if (preferences.getBoolean("loggedInAccountLocked", false)) {
        startingVisibility = "private";
    }

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

    // Setup the main text field.
    setEditTextMimeTypes(null); // new String[] { "image/gif", "image/webp" }
    final int mentionColour = ThemeUtils.getColor(this, R.attr.compose_mention_color);
    SpanUtils.highlightSpans(textEditor.getText(), mentionColour);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateVisibleCharactersLeft();
        }

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

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

    // 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(' ');
        }
        textEditor.setText(builder);
        textEditor.setSelection(textEditor.length());
    }

    // 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.
    mediaQueued = new ArrayList<>();
    waitForMediaLatch = new CountUpDownLatch();
    statusAlreadyInFlight = false;

    // These can only be added after everything affected by the media queue is initialized.
    if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            addMediaToQueue(item.type, item.preview, item.uri, item.mediaSize);
        }
    } 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<>();
                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 = 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());
                    }
                }
            }
        }
    }
}