- Sharing Content between Android apps
- Sharing text
- Sharing HTML text
- Receiving text
- Sharing files and images
- Receiving files
- The Support Library is your friend
- Share Apps для Android
- Выбираем приложение для передачи файлов между android-устройствами: CM Transfer, ShareCloud и 4 Share Apps
- Оглавление
- Вступление
- реклама
- 4 Share Apps
- Основные возможности
- Дополнительные функции
- ShareCloud (Share Apps) для Андроид
Sharing Content between Android apps
Sharing is caring, as they say, but sharing on Android means something perhaps slightly different. ‘Sharing’ is really shorthand for sending content such as text, formatted text, files, or images between apps.
So if ‘sharing’ == sending content, it makes slightly more sense that it is implemented using ACTION_SEND (or ACTION_SEND_MULTIPLE) Intents and its dozen extras.
While that approach is perfectly valid, I prefer to use ShareCompat, a set of classes in the v4 Support Library designed to make it easy to build intents for sharing content.
Sharing text
Sharing plain text is, as you might imagine, a good place to start. In fact, there’s not a whole lot to it:
ShareCompat.IntentBuilder uses a fluent API where you can chain together multiple method calls, using only the ones you need. For sharing, one of the most important parts is picking the right mime type — this is how apps filter what type of content they can receive. By using text/plain, we signify that our Intent will only contain plain text. Then, of course, setText() is how we actually add the CharSequence to the Intent to send. And while you can certainly send styled text using setText(), there’s no guarantee that the receiving app will honor that styling, so you should ensure that the text is legible with or without styling.
You’ll note we then use resolveActivity() before calling startActivity(). As mentioned in Protecting Implicit Intents with Runtime Checks, this is critical to prevent an ActivityNotFoundException when there is no Activity available to handle the mime type you have selected. While probably not as much of a concern with text/plain, it may be much more common with other types.
Note: when you use startActivity(shareIntent), that respects any default apps the user has set (i.e., if they’ve previously selected sharing all “text/plain” items to a certain app). If you’d like to instead always show a disambiguation chooser, use the intent generated from IntentBuilder.createChooserIntent() as explained in the ACTION_CHOOSER documentation.
Sharing HTML text
Some apps, most notably email clients, also support formatting with HTML. The changes, compared to plain text, are fairly minor:
The differences here are that we use of setHtmlText() in place of setText() and a mime type of text/html replacing text/plain. Here ShareCompat actually does a little bit extra: setHtmlText() also uses Html.fromHtml() to create a fallback formatted text to pass along to the receiving app if you haven’t previously called setText() yourself.
Given that many of the apps that can receive HTML text are email clients, there’s a number of helper methods to set the subject, to:, cc:, and bcc: email addresses as well — consider adding at least a subject to any share intent for best compatibility with email apps.
Of course, you’ll still want to call resolveActivity() just as before — nothing changes there.
Receiving text
While the focus so far has been on the sending side, it is helpful to know exactly what is happening on the other side (if not just to build a simple receiving app to install on your emulator for testing purposes). Receiving Activities add an intent filter to the Activity:
The action is obviously the more critical part — without that there’s nothing that would denote this as an ACTION_SEND (the action behind sharing). The mime type, same as with our sending code, is also present here. What isn’t as obvious are the two categories. From the element documentation:
Note: In order to receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent filter. The methods startActivity() and startActivityForResult() treat all intents as if they declared the CATEGORY_DEFAULT category. If you do not declare it in your intent filter, no implicit intents will resolve to your activity.
So CATEGORY_DEFAULT is required for our use case. Then, CATEGORY_BROWSABLE allows web pages to natively share into apps without any extra effort required on the receiving side.
And to actually extract the information from the Intent, the useful ShareCompat.IntentReader can be used:
Similar to IntentBuilder, IntentReader is just a simple wrapper that make it easy to extract information.
Sharing files and images
While sending and receiving text is straightforward enough (create text, include it in Intent), sending files (and particularly images — the most common type by far) has an additional wrinkle: file permissions.
The simplest code you might try might look like
And that almost works — the tricky part is in getting a Uri to the File that other apps can actually read, particularly when it comes to Android 6.0 Marshmallow devices and runtime permissions (which include the now dangerous READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions).
My plea: don’t use Uri.fromFile(). It forces receiving apps to have the READ_EXTERNAL_STORAGE permission, won’t work at all if you are trying to share across users, and prior to KitKat, would require your app to have WRITE_EXTERNAL_STORAGE. And really important share targets, like Gmail, won’t have the READ_EXTERNAL_STORAGE permission — so it’ll just fail.
Instead, you can use URI permissions to grant other apps access to specific Uris. While URI permissions don’t work on file:// URIs as is generated by Uri.fromFile(), they do work on Uris associated with Content Providers. Rather than implement your own just for this, you can and should use FileProvider as explained in the File Sharing Training.
Once you have it set up, our code becomes:
Using FileProvider.getUriForFile(), you’ll get a Uri actually suitable for sending to another app — they’ll be able to read it without any storage permissions — instead, you are specifically granting them read permission with FLAG_GRANT_READ_URI_PERMISSION.
Note: we don’t call setType() anywhere when building our ShareCompat (even though in the video I did set it). As explained in the setDataAndType() Javadoc, the type is automatically inferred from the data URI using getContentResolver().getType(uriToImage). Since FileProvider returns the correct mime type automatically, we don’t need to manually specify a mime type at all.
If you’re interested in learning more about avoiding the storage permission, consider watching my Forget the Storage Permission talk or at least go through the slides, which covers this topic in depth at 14:55 (slide 11).
Receiving files
Receiving files isn’t too different from text because you’re still going to use ShareCompat.IntentReader. For example, to make a Bitmap out of an incoming file, it would look like:
Of course, you’re free to do whatever you want with the InputStream — watch out for images that are so large you hit an OutOfMemoryException. All of the things you know about loading Bitmaps still apply.
The Support Library is your friend
With both ShareCompat (and its IntentBuilder and IntentReader) and FileProvider in the v4 Support Library, you’ll be able to include sharing text, HTML text, and files in your app with the best practices by default.
Источник
Share Apps для Android
Оценка: |
0.00 /5 голосов — 0 |
Лицензия: | Бесплатная |
Версия: | 1.2.3 | Сообщить о новой версии |
Обновлено: | 12.04.2019 |
ОС: | Android 4.x, 5.x, 6.x, 7.x, 8.x, 9.x |
Интерфейс: | Английский |
Разработчик: | Catania Solutions |
Категория: | Обмен файлами |
Загрузок (сегодня/всего): | 0 / 660 | Статистика |
Размер: | 7,26 Мб |
СКАЧАТЬ |
Share Apps — программа позволяет поделиться установленными приложениями на вашем устройстве (можно передать ссылку на Google Play или непосредственно файл APK), отправлять их друзьям (с помощью сообщений, электронной почты, Bluetooth, WhatsApp, Facebook Messenger и т.д.) и создавать резервные копии.
Поддерживается отправка сразу нескольких файлов: пользователь может выбрать несколько приложений и нажать на кнопку «Поделиться», чтобы незамедлительно начать их отправку. Также имеется быстрый поиск, позволяющий легко найти приложение, которые нужно отправить.
Основные возможности приложения:
- Поддержка отправки приложений через электронную почту, Bluetooth, мессенджеры или любые другие установленные на вашем устройстве приложения с функцией передачи данных.
- Поддержка мгновенного поиска, помогающего вам быстро находить приложения, которые вы хотите отправить.
- Кэширование для более быстрой работы.
- В приложение включены инструкции с описанием процесса отправки файлов.
- Быстрая отправка приложений с помощью Bluetooth.
Источник
Выбираем приложение для передачи файлов между android-устройствами: CM Transfer, ShareCloud и 4 Share Apps
Оглавление
Вступление
реклама
Мой коллега ранее рассматривал подобные приложения, но тогда речь шла о взаимодействии компьютера и смартфона, либо наоборот. Сегодня же мы поговорим о передаче файлов между устройствами на Android, для чего были подобраны программы именно этой направленности.
Действительно, по Bluetooth особо игры и мультимедиа не покидаешь, а здесь нам предлагают высокую скорость обмена информацией, резервное копирование и управление программами. Причем передача может осуществляться как с интернетом, так и без него. Весьма интересно, согласитесь.
Итак, первым пойдет универсальное решение от Cheetah Mobile (противоречивый Clean Master помните? Так это их рук дело). Приложение умеет просто и быстро передавать мультимедиа, обещая скорость в 160 раз выше, чем с Bluetooth. Смелое заявление (версию «гнилого зуба» не указали ведь), а значит, надо проверить. Второй пациент – ShareCloud умеет докучи еще обмениваться файлами между различными мессенджерами, создавать резервные копии программ и передавать их сразу несколько. О как! 4 Share Apps – это по сути аналог вышеописанного приложения, но с заявкой на стабильность. В общем, не буду ходить вокруг да около, а начну.
В качестве тестового оборудования использовались планшет DEXP Ursus 8EV2 3G (Android 4.4.2, процессор MT8382, 4 x Cortex-A7 1.3 ГГц, видеоядро Mali-400 MP2, 1 Гбайт ОЗУ, аккумулятор 4 000 мАч, 3G-модуль, Wi-Fi 802.11b/g/n) и смартфон Homtom HT3 Pro (Android 5.1 Lollipop, процессор MT6735P, 4 x Cortex-A53 1.0 ГГц, 64-бит, видеоядро Mali-T720, 2 Гбайт ОЗУ, аккумулятор 3 000 мАч, 4G-модуль, Wi-Fi 802.11b/g/n).
Источник
4 Share Apps
4 Share Apps – это приложение на Android, с помощью которого можно обмениваться файлами между несколькими устройствами. Данный мобильный клиент позволит забыть о том, как это – долго передавать файлы по Bluetooth, а также избавит Вас от покупки нового USB-кабеля вместо потерянного старого.
Основные возможности
Перед началом использования программы следует подключить устройства, между которыми будет происходить обмен данными, к одному хотспоту. Затем можно приступать к запуску программы. Девайс, с которого будет осуществляться передача данных, просканирует подключенные к Wi-Fi устройства, после чего пользователь должен выделить нужные файлы и выбрать необходимый телефон в списке подключенных к беспроводной сети.
4 Share Apps допускает передачу наиболее распространенных типов файлов: видео, музыки, электронных книг. Приложение не ограничивает юзеров в объеме передаваемых данных и обеспечивает скорость вплоть до 20 Мб/с, что позволит быстро скачивать даже объемные файлы.
Дополнительные функции
Кроме своих основных функций 4 Share App умеет создавать резервные копии приложений с SD-карты и транслирует список программ, чаще всего передаваемых между пользователями с помощью данного клиента. Если Вы хотите найти для себя что-то новое и интересное, можете пролистать список популярных приложений, но будьте внимательны, ведь в нем содержится рекламный контент. Все рекламируемые приложения содержат оповещение о том, что это реклама, поэтому «обойти» эти навязанные рекомендации не составит труда. Зато наличие рекламы позволяет разработчикам из 4Share предоставлять свою программу пользователям совершенно бесплатно.
Источник
ShareCloud (Share Apps) для Андроид
ShareCloud (Share Apps) – универсальная программа для передачи любых файлов с Андроид. С ShareCloud вы сможете с легкостью делиться изображениями, музыкой, видео, приложениями, фотографиями и другими файлами всего лишь одним движением.
Apps Share также пользователи смогут делиться ссылками на установленные приложения, ссылками на приложения в магазине Google Play. Программа умеет сортировать список приложений по названию, времени установки или размеру, а также осуществлять поиск по их имени. Системная утилита позволит вам делиться файлами как непосредственно, так и через интернет. Дизайн приятный, а расположение всех кнопок и вкладок логично. Функции расположены максимально удобно, многие действия сопровождаются подсказками. ShareCloud (Share Apps) позиционируется как мультифункциональное устройство для шарринга файлов. Предавать файлы можно через Bluetooth или WiFi сеть, при этом не тратя трафик. Можно загружать документы в интернет хранилища или ваши аккаунты в социальных сетях и мессенджерах. Для удобства поддерживается пакетная отправка.
Ключевые возможности ShareCloud на Android:
- делитесь файлами в одно движение;
- создание резервных копий музыки, фотографий и прочих файлов;
- делиться сразу несколькими файлами одновременно;
- сортировка по типу (видео, музыка, картинки);
- возможность создание бэкапов на SD-карте или в Dropbox;
- передача любых файлов;
- передача файлов через Bluetooth или Wi-Fi;
- функция быстрого поиска;
- толковый файловый менеджер с актуальными категориями;
- приятный дизайн;
- продуманный интерфейс;
- возможность делиться apk файлами и установленными программами.
На нашем сайте вы можете бесплатно скачать ShareCloud (Share Apps) на Андроид по ссылке, которая находится ниже.
Источник