Example usage for android.content Intent setPackage

List of usage examples for android.content Intent setPackage

Introduction

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

Prototype

public @NonNull Intent setPackage(@Nullable String packageName) 

Source Link

Document

(Usually optional) Set an explicit application package name that limits the components this Intent will resolve to.

Usage

From source file:org.chromium.chrome.browser.tab.Tab.java

/**
 * @return Intent that tells Chrome to bring an Activity for a particular Tab back to the
 *         foreground, or null if this isn't possible.
 *//*from   ww w.  j  a  v  a2 s . co  m*/
@Nullable
public static Intent createBringTabToFrontIntent(int tabId) {
    // Iterate through all {@link CustomTab}s and check whether the given tabId belongs to a
    // {@link CustomTab}. If so, return null as the client app's task cannot be foregrounded.
    List<WeakReference<Activity>> list = ApplicationStatus.getRunningActivities();
    for (WeakReference<Activity> ref : list) {
        Activity activity = ref.get();
        if (activity instanceof CustomTabActivity && ((CustomTabActivity) activity).getActivityTab() != null
                && tabId == ((CustomTabActivity) activity).getActivityTab().getId()) {
            return null;
        }
    }

    String packageName = ContextUtils.getApplicationContext().getPackageName();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.putExtra(Browser.EXTRA_APPLICATION_ID, packageName);
    intent.putExtra(TabOpenType.BRING_TAB_TO_FRONT.name(), tabId);
    intent.setPackage(packageName);
    return intent;
}

From source file:com.aimfire.main.MainActivity.java

/**
 * share only to certain apps. code based on "http://stackoverflow.com/questions/
 * 9730243/how-to-filter-specific-apps-for-action-send-intent-and-set-a-different-
 * text-for/18980872#18980872"/*  ww  w  . java  2s .c om*/
 *
 * "copy link" inspired by http://cketti.de/2016/06/15/share-url-to-clipboard/
 *
 * in general, "deep linking" is supported by the apps below. Facebook, Wechat,
 * Telegram are exceptions. click on the link would bring users to the landing
 * page.
 *
 * Facebook doesn't take our EXTRA_TEXT so user will have to "copy link" first
 * then paste the link
 */
private void inviteFriend() {
    mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_INVITE, null);

    Resources resources = getResources();

    /*
     * construct link
     */
    String appLink = resources.getString(R.string.app_store_link);

    /*
     * message subject and text
     */
    String emailSubject, emailText, twitterText;

    emailSubject = resources.getString(R.string.emailSubjectInviteFriend);
    emailText = resources.getString(R.string.emailBodyInviteFriend) + appLink;
    twitterText = resources.getString(R.string.emailBodyInviteFriend) + appLink + ", "
            + resources.getString(R.string.app_hashtag);

    Intent emailIntent = new Intent();
    emailIntent.setAction(Intent.ACTION_SEND);
    // Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
    //emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_native)));
    emailIntent.setType("message/rfc822");

    PackageManager pm = getPackageManager();
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");

    Intent openInChooser = Intent.createChooser(emailIntent, resources.getString(R.string.share_chooser_text));

    List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
    List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
    for (int i = 0; i < resInfo.size(); i++) {
        // Extract the label, append it, and repackage it in a LabeledIntent
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        if (packageName.contains("android.email")) {
            emailIntent.setPackage(packageName);
        } else if (packageName.contains("twitter") || packageName.contains("facebook")
                || packageName.contains("whatsapp") || packageName.contains("tencent.mm") || //wechat
                packageName.contains("line") || packageName.contains("skype") || packageName.contains("viber")
                || packageName.contains("kik") || packageName.contains("sgiggle") || //tango
                packageName.contains("kakao") || packageName.contains("telegram")
                || packageName.contains("nimbuzz") || packageName.contains("hike")
                || packageName.contains("imoim") || packageName.contains("bbm")
                || packageName.contains("threema") || packageName.contains("mms")
                || packageName.contains("android.apps.messaging") || //google messenger
                packageName.contains("android.talk") || //google hangouts
                packageName.contains("android.gm")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            if (packageName.contains("twitter")) {
                intent.putExtra(Intent.EXTRA_TEXT, twitterText);
            } else if (packageName.contains("facebook")) {
                /*
                 * the warning below is wrong! at least on GS5, Facebook client does take
                 * our text, however it seems it takes only the first hyperlink in the
                 * text.
                 *
                 * Warning: Facebook IGNORES our text. They say "These fields are intended
                 * for users to express themselves. Pre-filling these fields erodes the
                 * authenticity of the user voice."
                 * One workaround is to use the Facebook SDK to post, but that doesn't
                 * allow the user to choose how they want to share. We can also make a
                 * custom landing page, and the link will show the <meta content ="...">
                 * text from that page with our link in Facebook.
                 */
                intent.putExtra(Intent.EXTRA_TEXT, appLink);
            } else if (packageName.contains("tencent.mm")) //wechat
            {
                /*
                 * wechat appears to do this similar to Facebook
                 */
                intent.putExtra(Intent.EXTRA_TEXT, appLink);
            } else if (packageName.contains("android.gm")) {
                // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
                intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
                //intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_gmail)));
                intent.setType("message/rfc822");
            } else if (packageName.contains("android.apps.docs")) {
                /*
                 * google drive - no reason to send link to it
                 */
                continue;
            } else {
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
            }

            intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }

    /*
     *  create "Copy Link To Clipboard" Intent
     */
    Intent clipboardIntent = new Intent(this, CopyToClipboardActivity.class);
    clipboardIntent.setData(Uri.parse(appLink));
    intentList.add(new LabeledIntent(clipboardIntent, getPackageName(),
            getResources().getString(R.string.clipboard_activity_name), R.drawable.ic_copy_link));

    // convert intentList to array
    LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);

    openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
    startActivity(openInChooser);
}

From source file:me.spadival.podmode.PodModeService.java

public void broadcastMediaButtons(int keyCode, String app) {
    long eventtime = SystemClock.uptimeMillis();

    Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
    KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, keyCode, 0);
    downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
    if (app != null)
        downIntent.setPackage(app);

    sendOrderedBroadcast(downIntent, null);

    eventtime = SystemClock.uptimeMillis();

    Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
    KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, keyCode, 0);
    upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
    if (app != null)
        upIntent.setPackage(app);/*w w  w .j a va  2  s . com*/

    sendOrderedBroadcast(upIntent, null);

}

From source file:com.android.calendar.EventInfoFragment.java

private void updateCustomAppButton() {
    buttonSetup: {/*from w w w .  j  av a 2  s.  c  o m*/
        final Button launchButton = (Button) mView.findViewById(R.id.launch_custom_app_button);
        if (launchButton == null)
            break buttonSetup;

        final String customAppPackage = mEventCursor.getString(EVENT_INDEX_CUSTOM_APP_PACKAGE);
        final String customAppUri = mEventCursor.getString(EVENT_INDEX_CUSTOM_APP_URI);

        if (TextUtils.isEmpty(customAppPackage) || TextUtils.isEmpty(customAppUri))
            break buttonSetup;

        PackageManager pm = mContext.getPackageManager();
        if (pm == null)
            break buttonSetup;

        ApplicationInfo info;
        try {
            info = pm.getApplicationInfo(customAppPackage, 0);
            if (info == null)
                break buttonSetup;
        } catch (NameNotFoundException e) {
            break buttonSetup;
        }

        Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
        final Intent intent = new Intent(CalendarContract.ACTION_HANDLE_CUSTOM_EVENT, uri);
        intent.setPackage(customAppPackage);
        intent.putExtra(CalendarContract.EXTRA_CUSTOM_APP_URI, customAppUri);
        intent.putExtra(EXTRA_EVENT_BEGIN_TIME, mStartMillis);

        // See if we have a taker for our intent
        if (pm.resolveActivity(intent, 0) == null)
            break buttonSetup;

        Drawable icon = pm.getApplicationIcon(info);
        if (icon != null) {

            Drawable[] d = launchButton.getCompoundDrawables();
            icon.setBounds(0, 0, mCustomAppIconSize, mCustomAppIconSize);
            launchButton.setCompoundDrawables(icon, d[1], d[2], d[3]);
        }

        CharSequence label = pm.getApplicationLabel(info);
        if (label != null && label.length() != 0) {
            launchButton.setText(label);
        } else if (icon == null) {
            // No icon && no label. Hide button?
            break buttonSetup;
        }

        // Launch custom app
        launchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    startActivityForResult(intent, 0);
                } catch (ActivityNotFoundException e) {
                    // Shouldn't happen as we checked it already
                    setVisibilityCommon(mView, R.id.launch_custom_app_container, View.GONE);
                }
            }
        });

        setVisibilityCommon(mView, R.id.launch_custom_app_container, View.VISIBLE);
        return;

    }

    setVisibilityCommon(mView, R.id.launch_custom_app_container, View.GONE);
    return;
}

From source file:com.android.calendar.EventInfoFragment.java

/**
 * Generates an .ics formatted file with the event info and launches intent chooser to
 * share said file/*from  w  ww  . j ava2 s .  c o m*/
 */
public void shareEvent(ShareType type) {
    VCalendar calendar = generateVCalendar();
    // create and share ics file
    boolean isShareSuccessful = false;
    try {
        // event title serves as the file name prefix
        String filePrefix = calendar.getFirstEvent().getProperty(VEvent.SUMMARY);
        if (filePrefix == null || filePrefix.length() < 3) {
            // default to a generic filename if event title doesn't qualify
            // prefix length constraint is imposed by File#createTempFile
            filePrefix = "invite";
        }

        filePrefix = filePrefix.replaceAll("\\W+", " ");

        if (!filePrefix.endsWith(" ")) {
            filePrefix += " ";
        }

        File dir;
        if (type == ShareType.SDCARD) {
            dir = EXPORT_SDCARD_DIRECTORY;
            if (!dir.exists()) {
                dir.mkdir();
            }
        } else {
            dir = mActivity.getExternalCacheDir();
        }

        File inviteFile = IcalendarUtils.createTempFile(filePrefix, ".ics", dir);

        if (IcalendarUtils.writeCalendarToFile(calendar, inviteFile)) {
            if (type == ShareType.INTENT) {
                inviteFile.setReadable(true, false); // set world-readable
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(inviteFile));
                // the ics file is sent as an extra, the receiving application decides whether
                // to parse the file to extract calendar events or treat it as a regular file
                shareIntent.setType("application/octet-stream");

                Intent chooserIntent = Intent.createChooser(shareIntent,
                        getResources().getString(R.string.cal_share_intent_title));

                // The MMS app only responds to "text/x-vcalendar" so we create a chooser intent
                // that includes the targeted mms intent + any that respond to the above general
                // purpose "application/octet-stream" intent.
                File vcsInviteFile = File.createTempFile(filePrefix, ".vcs", mActivity.getExternalCacheDir());

                // for now , we are duplicating ics file and using that as the vcs file
                // TODO: revisit above
                if (IcalendarUtils.copyFile(inviteFile, vcsInviteFile)) {
                    Intent mmsShareIntent = new Intent();
                    mmsShareIntent.setAction(Intent.ACTION_SEND);
                    mmsShareIntent.setPackage("com.android.mms");
                    mmsShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcsInviteFile));
                    mmsShareIntent.setType("text/x-vcalendar");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { mmsShareIntent });
                }
                startActivity(chooserIntent);
            } else {
                if (!mInNonUiMode) {
                    String msg = getString(R.string.cal_export_succ_msg);
                    Toast.makeText(mActivity, String.format(msg, inviteFile), Toast.LENGTH_SHORT).show();
                }
            }
            isShareSuccessful = true;

        } else {
            // error writing event info to file
            isShareSuccessful = false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        isShareSuccessful = false;
    }

    if (!isShareSuccessful) {
        Log.e(TAG, "Couldn't generate ics file");
        Toast.makeText(mActivity, R.string.error_generating_ics, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.tct.mail.browse.MessageAttachmentBar.java

@Override
public void viewAttachment() {
    if (mAttachment.contentUri == null) {
        LogUtils.e(LOG_TAG, "viewAttachment with null content uri");
        return;//from  ww  w.  j  a  v  a 2 s . c  o  m
    }

    //TS: junwei-xu 2016-03-16 EMAIL BUGFIX-1740140 ADD_S
    if (MimeType.isXvcardType(mAttachment.getContentType())) {
        importXvcard(mAttachment, mAttachment.getContentType());
        return;
    }
    //TS: junwei-xu 2016-03-16 EMAIL BUGFIX-1740140 ADD_E
    //TS: zheng.zou 2016-04-14 EMAIL BUGFIX-1779964 MOD_S
    //NOTE:Here for no screen flash when view image with Gallery,gallery call us must remove
    //any Intent TASK TAG...(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    //TS: zheng.zou 2016-04-14 EMAIL BUGFIX-1779964 MOD_E
    final String contentType = mAttachment.getContentType();
    // TS: zhaotianyong 2014-11-25 EMAIL BUGFIX-847926 ADD_S
    String str = mAttachment.contentUri.toString();
    // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912160 MOD_S
    if (str.endsWith("RAW") && mAttachment.getName() != null)
    // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912160 MOD_E
    {
        // TS: zhaotianyong 2015-02-14 EMAIL BUGFIX-928905 MOD_S
        str = str.replace("RAW", "RAW/" + mAttachment.getName());
        // TS: zhaotianyong 2015-02-14 EMAIL BUGFIX-928905 MOD_E
    }
    // TS: zhaotianyong 2014-11-25 EMAIL BUGFIX-847926 ADD_E
    //TS: zhonghua.tuo 2015-3-3 EMAIL BUGFIX_936728 MOD_S
    //TS: xiangnan.zhou 2016-03-17 EMAIL BUGFIX_1785573 MOD_S
    //NOTE:remove NONE-Text/HTML judge,here if file exist in local,just use file:///,it means
    //use real uri
    if (fileExist()) {//TS: zhaotianyong 2015-03-13 EMAIL BUGFIX_945771 MOD
        Utils.setIntentDataAndTypeAndNormalize(intent, mAttachment.realUri, contentType);
    } else {
        Utils.setIntentDataAndTypeAndNormalize(intent, Uri.parse(str)/*mAttachment.contentUri*/, contentType);
    }
    //TS: xiangnan.zhou 2016-03-17 EMAIL BUGFIX_1785573 MOD_S
    //TS: zhonghua.tuo 2015-3-3 EMAIL BUGFIX_936728 MOD_E
    // For EML files, we want to open our dedicated
    // viewer rather than let any activity open it.
    if (MimeType.isEmlMimeType(contentType)) {
        intent.setPackage(getContext().getPackageName());
        intent.putExtra(AccountFeedbackActivity.EXTRA_ACCOUNT_URI, mAccount != null ? mAccount.uri : null);
    }

    try {
        getContext().startActivity(intent);
    } catch (ActivityNotFoundException e) {
        // couldn't find activity for View intent
        LogUtils.e(LOG_TAG, e, "Couldn't find Activity for intent");
        // TS: zhaotianyong 2015-05-19 EMAIL BUGFIX-1006010 MOD_S
        // TS: zhaotianyong 2015-05-05 EMAIL BUGFIX-989483 ADD_S
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        int dialogMessage = R.string.no_application_found;
        builder.setTitle(R.string.more_info_attachment).setMessage(dialogMessage).show();
        // TS: zhaotianyong 2015-05-05 EMAIL BUGFIX-989483 ADD_E
        // TS: zhaotianyong 2015-05-19 EMAIL BUGFIX-1006010 MOD_E
    }
}

From source file:com.ifoer.expeditionphone.MainActivity.java

private void openApp() throws NameNotFoundException {
    PackageInfo pi = getPackageManager().getPackageInfo("com.cnlaunch.golo3", 0);
    Intent resolveIntent = new Intent("android.intent.action.MAIN", null);
    resolveIntent.addCategory("android.intent.category.LAUNCHER");
    resolveIntent.setPackage(pi.packageName);
    ResolveInfo ri = (ResolveInfo) getPackageManager().queryIntentActivities(resolveIntent, 0).iterator()
            .next();/*from w  w w .j a  v  a 2s  . c  om*/
    if (ri != null) {
        String packageName1 = ri.activityInfo.packageName;
        String className = ri.activityInfo.name;
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        intent.setComponent(new ComponentName(packageName1, className));
        startActivity(intent);
    }
}

From source file:com.github.michalbednarski.intentslab.editor.IntentGeneralFragment.java

@Override
public void updateEditedIntent(Intent editedIntent) {
    // Intent action

    if (mAvailbleActions != null) {
        editedIntent.setAction((String) mActionsSpinner.getSelectedItem());
    } else {/*from w  ww .j av  a 2  s.c o m*/
        String action = mActionText.getText().toString();
        if ("".equals(action)) {
            action = null;
        }
        editedIntent.setAction(action);
    }

    // Categories
    {
        // Clear categories (why there's no api for this)
        Set<String> origCategories = editedIntent.getCategories();
        if (origCategories != null) {
            for (String category : origCategories.toArray(new String[origCategories.size()])) {
                editedIntent.removeCategory(category);
            }
        }
    }
    // Fill categories
    if (mCategoryCheckBoxes != null) {
        // Fill categories from checkboxes
        for (CheckBox cb : mCategoryCheckBoxes) {
            String category = (String) cb.getTag();
            if (cb.isChecked()) {
                editedIntent.addCategory(category);
            }
        }
    } else {
        // Fill categories from textfields
        for (TextView categoryTextView : mCategoryTextInputs) {
            editedIntent.addCategory(categoryTextView.getText().toString());
        }
    }

    // Intent data (Uri) and type (MIME)
    String data = mDataText.getText().toString();
    editedIntent.setDataAndType(data.equals("") ? null : Uri.parse(data), getDataType());

    // Package name
    {
        String packageName = mPackageNameText.getText().toString();
        if ("".equals(packageName)) {
            editedIntent.setPackage(null);
        } else {
            editedIntent.setPackage(packageName);
        }
    }

    // Set component for explicit intent
    updateIntentComponent();
}