androidx.core.content.pm.ShortcutInfoCompat Java Examples

The following examples show how to use androidx.core.content.pm.ShortcutInfoCompat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConversationActivity.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static void addIconToHomeScreen(@NonNull Context context,
                                        @NonNull Bitmap bitmap,
                                        @NonNull Recipient recipient)
{
  IconCompat icon = IconCompat.createWithAdaptiveBitmap(bitmap);
  String     name = recipient.isLocalNumber() ? context.getString(R.string.note_to_self)
                                                : recipient.getDisplayName(context);

  ShortcutInfoCompat shortcutInfoCompat = new ShortcutInfoCompat.Builder(context, recipient.getId().serialize() + '-' + System.currentTimeMillis())
                                                                .setShortLabel(name)
                                                                .setIcon(icon)
                                                                .setIntent(ShortcutLauncherActivity.createIntent(context, recipient.getId()))
                                                                .build();

  if (ShortcutManagerCompat.requestPinShortcut(context, shortcutInfoCompat, null)) {
    Toast.makeText(context, context.getString(R.string.ConversationActivity_added_to_home_screen), Toast.LENGTH_LONG).show();
  }

  bitmap.recycle();
}
 
Example #2
Source File: PhonkScriptHelper.java    From PHONK with GNU General Public License v3.0 6 votes vote down vote up
public static void addShortcut(Context c, String folder, String name) {
    Project p = new Project(folder, name);

    Intent.ShortcutIconResource icon;
    icon = Intent.ShortcutIconResource.fromContext(c, R.drawable.app_icon);

    if (ShortcutManagerCompat.isRequestPinShortcutSupported(c)) {
        Intent shortcutIntent = new Intent(c, AppRunnerActivity.class);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        shortcutIntent.putExtra(Project.NAME, p.getName());
        shortcutIntent.putExtra(Project.FOLDER, p.getFolder());
        shortcutIntent.setAction(Intent.ACTION_MAIN);

        ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(c, folder + "/" + name)
                .setIntent(shortcutIntent) // !!! intent's action must be set on oreo
                .setShortLabel(name)
                .setIcon(IconCompat.createWithResource(c, R.drawable.app_icon))
                .build();
        ShortcutManagerCompat.requestPinShortcut(c, shortcutInfo, null);
    }
}
 
Example #3
Source File: PrivateActivity.java    From SimplicityBrowser with MIT License 6 votes vote down vote up
private AlertDialog createExitDialog() {
    return new AlertDialog.Builder(PrivateActivity.this)
            .setPositiveButton(getString(R.string.ok), (dialog, which) -> {
                Intent intent1 = new Intent(getApplicationContext(), MainActivity.class);
                intent1.setAction(Intent.ACTION_MAIN);
                intent1.setData(Uri.parse(mSearchView.getText().toString()));
                ShortcutInfoCompat pinShortcutInfo = new ShortcutInfoCompat.Builder(PrivateActivity.this, shortcutNameEditText.getText().toString())
                        .setShortLabel(shortcutNameEditText.getText().toString())
                        .setIcon(IconCompat.createWithBitmap(StaticUtils.createScaledBitmap(StaticUtils.getCroppedBitmap(favoriteIcon), 300, 300)))
                        .setIntent(intent1)
                        .build();
                ShortcutManagerCompat.requestPinShortcut(PrivateActivity.this, pinShortcutInfo, null);
            })
            .setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
                // nothing to do here
            })
            .setCancelable(true)
            .create();
}
 
Example #4
Source File: MainActivity.java    From c3nav-android with Apache License 2.0 6 votes vote down vote up
@JavascriptInterface
public void createShortcut(String url, String title) {
    Intent shortcutIntent = new Intent(getApplicationContext(),
            MainActivity.class);
    shortcutIntent.setAction(Intent.ACTION_MAIN);
    shortcutIntent.setData(Uri.parse(url));

    if (!ShortcutManagerCompat.isRequestPinShortcutSupported(getApplicationContext())) {
        Toast.makeText(MainActivity.this, R.string.shortcut_not_supported, Toast.LENGTH_LONG).show();
    }

    final ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(getApplicationContext(), url)
            .setShortLabel(title)
            .setLongLabel(title)
            .setIcon(IconCompat.createWithResource(getApplicationContext(), R.mipmap.ic_launcher_36c3))
            .setIntent(shortcutIntent)
            .build();

    ShortcutManagerCompat.requestPinShortcut(getApplicationContext(), shortcutInfo, null);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        Toast.makeText(MainActivity.this, R.string.shortcut_created, Toast.LENGTH_SHORT).show();
    }

}
 
Example #5
Source File: SharingShortcutsManager.java    From android-SharingShortcuts with Apache License 2.0 5 votes vote down vote up
/**
 * Publish the list of dynamics shortcuts that will be used in Direct Share.
 * <p>
 * For each shortcut, we specify the categories that it will be associated to,
 * the intent that will trigger when opened as a static launcher shortcut,
 * and the Shortcut ID between other things.
 * <p>
 * The Shortcut ID that we specify in the {@link ShortcutInfoCompat.Builder} constructor will
 * be received in the intent as {@link Intent#EXTRA_SHORTCUT_ID}.
 * <p>
 * In this code sample, this method is completely static. We are always setting the same sharing
 * shortcuts. In a real-world example, we would replace existing shortcuts depending on
 * how the user interacts with the app as often as we want to.
 */
public void pushDirectShareTargets(@NonNull Context context) {
    ArrayList<ShortcutInfoCompat> shortcuts = new ArrayList<>();

    // Category that our sharing shortcuts will be assigned to
    Set<String> contactCategories = new HashSet<>();
    contactCategories.add(CATEGORY_TEXT_SHARE_TARGET);

    // Adding maximum number of shortcuts to the list
    for (int id = 0; id < MAX_SHORTCUTS; ++id) {
        Contact contact = Contact.byId(id);

        // Item that will be sent if the shortcut is opened as a static launcher shortcut
        Intent staticLauncherShortcutIntent = new Intent(Intent.ACTION_DEFAULT);

        // Creates a new Sharing Shortcut and adds it to the list
        // The id passed in the constructor will become EXTRA_SHORTCUT_ID in the received Intent
        shortcuts.add(new ShortcutInfoCompat.Builder(context, Integer.toString(id))
                .setShortLabel(contact.getName())
                // Icon that will be displayed in the share target
                .setIcon(IconCompat.createWithResource(context, contact.getIcon()))
                .setIntent(staticLauncherShortcutIntent)
                // Make this sharing shortcut cached by the system
                // Even if it is unpublished, it can still appear on the sharesheet
                .setLongLived()
                .setCategories(contactCategories)
                // Person objects are used to give better suggestions
                .setPerson(new Person.Builder()
                        .setName(contact.getName())
                        .build())
                .build());
    }

    ShortcutManagerCompat.addDynamicShortcuts(context, shortcuts);
}
 
Example #6
Source File: SharingShortcutsManager.java    From storage-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Publish the list of dynamics shortcuts that will be used in Direct Share.
 * <p>
 * For each shortcut, we specify the categories that it will be associated to,
 * the intent that will trigger when opened as a static launcher shortcut,
 * and the Shortcut ID between other things.
 * <p>
 * The Shortcut ID that we specify in the {@link ShortcutInfoCompat.Builder} constructor will
 * be received in the intent as {@link Intent#EXTRA_SHORTCUT_ID}.
 * <p>
 * In this code sample, this method is completely static. We are always setting the same sharing
 * shortcuts. In a real-world example, we would replace existing shortcuts depending on
 * how the user interacts with the app as often as we want to.
 */
public void pushDirectShareTargets(@NonNull Context context) {
    ArrayList<ShortcutInfoCompat> shortcuts = new ArrayList<>();

    // Category that our sharing shortcuts will be assigned to
    Set<String> contactCategories = new HashSet<>();
    contactCategories.add(CATEGORY_TEXT_SHARE_TARGET);

    // Adding maximum number of shortcuts to the list
    for (int id = 0; id < MAX_SHORTCUTS; ++id) {
        Contact contact = Contact.byId(id);

        // Item that will be sent if the shortcut is opened as a static launcher shortcut
        Intent staticLauncherShortcutIntent = new Intent(Intent.ACTION_DEFAULT);

        // Creates a new Sharing Shortcut and adds it to the list
        // The id passed in the constructor will become EXTRA_SHORTCUT_ID in the received Intent
        shortcuts.add(new ShortcutInfoCompat.Builder(context, Integer.toString(id))
                .setShortLabel(contact.getName())
                // Icon that will be displayed in the share target
                .setIcon(IconCompat.createWithResource(context, contact.getIcon()))
                .setIntent(staticLauncherShortcutIntent)
                // Make this sharing shortcut cached by the system
                // Even if it is unpublished, it can still appear on the sharesheet
                .setLongLived()
                .setCategories(contactCategories)
                // Person objects are used to give better suggestions
                .setPerson(new Person.Builder()
                        .setName(contact.getName())
                        .build())
                .build());
    }

    ShortcutManagerCompat.addDynamicShortcuts(context, shortcuts);
}
 
Example #7
Source File: Shortcuts.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
static ShortcutInfoCompat.Builder getShortcut(Context context, InternetAddress address) {
    String name = address.getPersonal();
    String email = address.getAddress();

    Uri lookupUri = null;
    boolean contacts = Helper.hasPermission(context, Manifest.permission.READ_CONTACTS);
    if (contacts) {
        ContentResolver resolver = context.getContentResolver();
        try (Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                new String[]{
                        ContactsContract.CommonDataKinds.Photo.CONTACT_ID,
                        ContactsContract.Contacts.LOOKUP_KEY,
                        ContactsContract.Contacts.DISPLAY_NAME
                },
                ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
                new String[]{email}, null)) {
            if (cursor != null && cursor.moveToNext()) {
                int colContactId = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.CONTACT_ID);
                int colLookupKey = cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
                int colDisplayName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

                long contactId = cursor.getLong(colContactId);
                String lookupKey = cursor.getString(colLookupKey);
                String displayName = cursor.getString(colDisplayName);

                lookupUri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey);
                if (!TextUtils.isEmpty(displayName))
                    name = displayName;
            }
        }
    }

    return getShortcut(context, email, name, lookupUri);
}
 
Example #8
Source File: AppsListFragment.java    From J2ME-Loader with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onContextItemSelected(MenuItem item) {
	AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
	int index = info.position;
	AppItem appItem = adapter.getItem(index);
	switch (item.getItemId()) {
		case R.id.action_context_shortcut:
			Bitmap bitmap = BitmapFactory.decodeFile(appItem.getImagePathExt());
			Intent launchIntent = new Intent(Intent.ACTION_DEFAULT,
					Uri.parse(appItem.getPath()), getActivity(), ConfigActivity.class);
			ShortcutInfoCompat.Builder shortcutInfoCompatBuilder =
					new ShortcutInfoCompat.Builder(getActivity(), appItem.getTitle())
							.setIntent(launchIntent)
							.setShortLabel(appItem.getTitle());
			if (bitmap != null) {
				shortcutInfoCompatBuilder.setIcon(IconCompat.createWithBitmap(bitmap));
			} else {
				shortcutInfoCompatBuilder.setIcon(IconCompat.createWithResource(getActivity(), R.mipmap.ic_launcher));
			}
			ShortcutManagerCompat.requestPinShortcut(getActivity(), shortcutInfoCompatBuilder.build(), null);
			break;
		case R.id.action_context_rename:
			showRenameDialog(index);
			break;
		case R.id.action_context_settings:
			Config.startApp(getActivity(), appItem.getPath(), true);
			break;
		case R.id.action_context_delete:
			showDeleteDialog(index);
			break;
	}
	return super.onContextItemSelected(item);
}
 
Example #9
Source File: HomeScreen.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Create a shortcut via the AppCompat's shortcut manager.
 * <p>
 * On Android versions up to 7 shortcut will be created via system broadcast internally.
 * <p>
 * On Android 8+ the user will have the ability to add the shortcut manually
 * or let the system place it automatically.
 */
private static void installShortCutViaManager(Context context, Bitmap bitmap, String url, String title, boolean blockingEnabled, boolean requestDesktop) {
    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
        final IconCompat icon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) ?
                IconCompat.createWithAdaptiveBitmap(bitmap) : IconCompat.createWithBitmap(bitmap);
        final ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(context, UUID.randomUUID().toString())
                .setShortLabel(title)
                .setLongLabel(title)
                .setIcon(icon)
                .setIntent(createShortcutIntent(context, url, blockingEnabled, requestDesktop))
                .build();
        ShortcutManagerCompat.requestPinShortcut(context, shortcut, null);
    }
}
 
Example #10
Source File: DemoSettingFragment.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private void createShortcut() {
    Activity activity = getActivity();
    if (activity == null) {
        return;
    }
    Context context = activity.getApplicationContext();
    Intent shortcut = createDemoPageIntent();

    ShortcutInfoCompat.Builder builder = new ShortcutInfoCompat.Builder(context, CAMERA_DEMO_SHORTCUT_ID)
            .setIcon(IconCompat.createWithResource(context, getShortcutIconResource(mDemoInstaller)))
            .setShortLabel(getShortcutShortLabel(mDemoInstaller))
            .setLongLabel(getShortcutLongLabel(mDemoInstaller))
            .setIntent(shortcut);
    ComponentName mainActivity = getMainActivity(context);
    if (mainActivity != null) {
        builder.setActivity(mainActivity);
    }
    ShortcutInfoCompat info = builder.build();
    boolean result = ShortcutManagerCompat.requestPinShortcut(context, info, null);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        // OS 8以下の場合はOSが結果を表示しないので、自前で出す
        if (result) {
            showShurtcutResult(getString(R.string.demo_page_settings_button_create_shortcut_success));
        } else {
            showShurtcutResult(getString(R.string.demo_page_settings_button_create_shortcut_error));
        }
    }
}
 
Example #11
Source File: Shortcuts.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
@NotNull
static ShortcutInfoCompat.Builder getShortcut(Context context, EntityContact contact) {
    return getShortcut(context, contact.email, contact.name, contact.avatar);
}
 
Example #12
Source File: Shortcuts.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
@NotNull
private static ShortcutInfoCompat.Builder getShortcut(Context context, String email, String name, String avatar) {
    return getShortcut(context, email, name, avatar == null ? null : Uri.parse(avatar));
}
 
Example #13
Source File: Shortcuts.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
@NotNull
private static ShortcutInfoCompat.Builder getShortcut(Context context, String email, String name, Uri avatar) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean identicons = prefs.getBoolean("identicons", false);
    boolean circular = prefs.getBoolean("circular", true);

    Intent intent = new Intent(context, ActivityMain.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.setAction(Intent.ACTION_SEND);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setData(Uri.parse("mailto:" + email));

    Bitmap bitmap = null;
    if (avatar != null &&
            Helper.hasPermission(context, Manifest.permission.READ_CONTACTS)) {
        // Create icon from bitmap because launcher might not have contacts permission
        InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(
                context.getContentResolver(), avatar);
        bitmap = BitmapFactory.decodeStream(is);
    }

    boolean identicon = false;
    if (bitmap == null) {
        int dp = Helper.dp2pixels(context, 96);
        if (identicons) {
            identicon = true;
            bitmap = ImageHelper.generateIdenticon(email, dp, 5, context);
        } else
            bitmap = ImageHelper.generateLetterIcon(email, name, dp, context);
    }

    bitmap = ImageHelper.makeCircular(bitmap,
            circular && !identicon ? null : Helper.dp2pixels(context, 3));

    IconCompat icon = IconCompat.createWithBitmap(bitmap);
    String id = (name == null ? email : "\"" + name + "\" <" + email + ">");
    Set<String> categories = new HashSet<>(Arrays.asList("eu.faircode.email.TEXT_SHARE_TARGET"));
    ShortcutInfoCompat.Builder builder = new ShortcutInfoCompat.Builder(context, id)
            .setIcon(icon)
            .setShortLabel(name == null ? email : name)
            .setLongLabel(name == null ? email : name)
            .setCategories(categories)
            .setIntent(intent);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        Person.Builder person = new Person.Builder()
                .setIcon(icon)
                .setName(name == null ? email : name)
                .setImportant(true);
        if (avatar != null)
            person.setUri(avatar.toString());
        builder.setPerson(person.build());
    }

    return builder;
}
 
Example #14
Source File: PreferenceActivity.java    From Aria2App with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void buildPreferences(@NonNull Context context) {
    MaterialCheckboxPreference nightMode = new MaterialCheckboxPreference.Builder(context)
            .defaultValue(PK.NIGHT_MODE.fallback())
            .key(PK.NIGHT_MODE.key())
            .build();
    nightMode.setTitle(R.string.prefs_nightMode);
    nightMode.setSummary(R.string.prefs_nightMode_summary);
    nightMode.setIcon(R.drawable.baseline_opacity_24);
    addPreference(nightMode);

    MaterialCheckboxPreference hideMetadata = new MaterialCheckboxPreference.Builder(context)
            .defaultValue(PK.A2_HIDE_METADATA.fallback())
            .key(PK.A2_HIDE_METADATA.key())
            .build();
    hideMetadata.setTitle(R.string.prefs_hideMetadata);
    hideMetadata.setSummary(R.string.prefs_hideMetadata_summary);
    hideMetadata.setIcon(R.drawable.baseline_link_24);
    addPreference(hideMetadata);

    MaterialSeekBarPreference updateRate = new MaterialSeekBarPreference.Builder(context)
            .minValue(1).maxValue(10).showValue(true)
            .key(PK.A2_UPDATE_INTERVAL.key())
            .defaultValue(PK.A2_UPDATE_INTERVAL.fallback())
            .build();
    updateRate.setTitle(R.string.prefs_updateRate);
    updateRate.setSummary(R.string.prefs_updateRate_summary);
    updateRate.setIcon(R.drawable.baseline_update_24);
    addPreference(updateRate);

    MaterialSeekBarPreference networkTimeout = new MaterialSeekBarPreference.Builder(context)
            .minValue(1).maxValue(60).showValue(true)
            .key(PK.A2_NETWORK_TIMEOUT.key())
            .defaultValue(PK.A2_NETWORK_TIMEOUT.fallback())
            .build();
    networkTimeout.setTitle(R.string.prefs_networkTimeout);
    networkTimeout.setSummary(R.string.prefs_networkTimeout_summary);
    networkTimeout.setIcon(R.drawable.baseline_network_check_24);
    addPreference(networkTimeout);

    MaterialMultiChoicePreference customDownloadInfo = new MaterialMultiChoicePreference.Builder(context)
            .entryValues(CustomDownloadInfo.Info.stringValues())
            .entries(CustomDownloadInfo.Info.formalValues(context))
            .defaultValue(CustomDownloadInfo.Info.DOWNLOAD_SPEED.name(), CustomDownloadInfo.Info.REMAINING_TIME.name())
            .showValueMode(AbsMaterialTextValuePreference.SHOW_ON_BOTTOM)
            .key(PK.A2_CUSTOM_INFO.key())
            .build();
    customDownloadInfo.setTitle(R.string.prefs_downloadDisplayInfo);
    customDownloadInfo.setSummary(R.string.prefs_downloadDisplayInfo_summary);
    customDownloadInfo.setIcon(R.drawable.baseline_info_outline_24);
    addPreference(customDownloadInfo);

    MaterialCheckboxPreference versionCheck = new MaterialCheckboxPreference.Builder(context)
            .key(PK.A2_CHECK_VERSION.key())
            .defaultValue(PK.A2_CHECK_VERSION.fallback())
            .build();
    versionCheck.setTitle(R.string.prefs_versionCheck);
    versionCheck.setSummary(R.string.prefs_versionCheck_summary);
    versionCheck.setIcon(R.drawable.baseline_verified_user_24);
    addPreference(versionCheck);

    MaterialCheckboxPreference bestTrackers = new MaterialCheckboxPreference.Builder(context)
            .key(PK.A2_ADD_BEST_TRACKERS.key())
            .defaultValue(PK.A2_ADD_BEST_TRACKERS.fallback())
            .build();
    bestTrackers.setTitle(R.string.prefs_addBestTrackers);
    bestTrackers.setSummary(R.string.prefs_addBestTrackers_summary);
    bestTrackers.setIcon(R.drawable.baseline_track_changes_24);
    addPreference(bestTrackers);

    MaterialCheckboxPreference skipWebViewDialog = new MaterialCheckboxPreference.Builder(context)
            .key(PK.A2_SKIP_WEBVIEW_DIALOG.key())
            .defaultValue(PK.A2_SKIP_WEBVIEW_DIALOG.fallback())
            .build();
    skipWebViewDialog.setTitle(R.string.prefs_skipWebViewDialog);
    skipWebViewDialog.setSummary(R.string.prefs_skipWebViewDialog_summary);
    // skipWebViewDialog.setIcon(R.drawable.baseline_track_changes_24);
    addPreference(skipWebViewDialog);

    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
        MaterialStandardPreference webviewShortcut = new MaterialStandardPreference(context);
        webviewShortcut.setTitle(R.string.addWebViewShortcutToHomePage);
        webviewShortcut.setSummary(R.string.addWebViewShortcutToHomePage_summary);
        webviewShortcut.setIcon(R.drawable.baseline_language_24);
        addPreference(webviewShortcut);

        webviewShortcut.setOnClickListener(v -> {
            ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(context, "#1")
                    .setIntent(new Intent(context, LoadingActivity.class)
                            .setAction(LoadingActivity.SHORTCUT_WEB_VIEW))
                    .setShortLabel(getString(R.string.webView) + " - " + getString(R.string.app_name))
                    .setIcon(IconCompat.createWithResource(context, R.drawable.baseline_language_colored_24))
                    .build();
            ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null);
        });
    }
}