Android share with email

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.

Читайте также:  Send sms android permission

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).

Читайте также:  Srv19 android ts v2 app file ts2 v177 apk

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.

Источник

Отправка E-Mail средствами Android

Привет хабр и привет всем!

В данной статье я покажу как реализуется отправка писем средствами самого Android, а также ещё один более интересный способ, но уже с применением внешней библиотеки, которая позволяет нам отсылать письма более приемлимыми для программиста способами.

Часть 1. Mail, просто Mail

  1. public class SimpleEMail extends Activity <
  2. Button send;
  3. EditText address, subject, emailtext;
  4. @Override
  5. public void onCreate(Bundle savedInstanceState) <
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.simple_email);
  8. // Наши поля и кнопка
  9. send = (Button) findViewById(R.id.emailsendbutton);
  10. address = (EditText) findViewById(R.id.emailaddress);
  11. subject = (EditText) findViewById(R.id.emailsubject);
  12. emailtext = (EditText) findViewById(R.id.emailtext);
  13. send.setOnClickListener( new OnClickListener() <
  14. @Override
  15. public void onClick(View v) <
  16. final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
  17. emailIntent.setType( «plain/text» );
  18. // Кому
  19. emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
  20. new String [] < address.getText().toString() >);
  21. // Зачем
  22. emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
  23. subject.getText().toString());
  24. // О чём
  25. emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
  26. emailtext.getText().toString());
  27. // С чем
  28. emailIntent.putExtra(
  29. android.content.Intent.EXTRA_STREAM,
  30. Uri .parse( «file://»
  31. + Environment.getExternalStorageDirectory()
  32. + «/Клипы/SOTY_ATHD.mp4» ));
  33. emailIntent.setType( «text/video» );
  34. // Поехали!
  35. SimpleEMail. this .startActivity(Intent.createChooser(emailIntent,
  36. «Отправка письма. » ));
  37. >
  38. >);
  39. >
  40. >

* This source code was highlighted with Source Code Highlighter .

Вот, код до безобразия прост. Правда можно еще проще: если нам лень создавать дополнительное Activity для ввода наших полей, то можно было бы просто запустить наш Intent.

Плюсы: Простая реализация, достаточно удобно для обратной связи.
Минусы: У пользователя должна быть настроенная программа приёма-передачи почтовых сообщений, без неё обрабатывать данный Intent будет некому.

Часть 2. Mail, анонимус Mail

Данный метод я использовал в своём проекте, обозначим для начала плюсы:

  • Не требует от пользователя настроенного клиента
  • Может быть полностью анонимным
  • Можно передавать все (в пределах разумного, конечно)

Для работы необходимы дополнительные библиотеки javamail-android.
Качаем их, и встраиваем в проект: Контекстное меню проекта > «Build Path» > «Add External Archives. » > «Наши файлы additional, mail, activation»

Читайте также:  Андроид адаптер для машины

Для настройки нам также понадобится почтовый ящик зарегистрированный на gmail.com (или любом другом yandex, mail и.т.п.) настройки вы можете посмотреть здесь. В данном случае он будет выступать в виде шлюза через которые будут проходить наши письма.

Начинаем настраивать:
MailSenderClass.java
В данном классе записаны настройки того сервера, через который будет передаваться ваше сообщение. Здесь у нас есть несколько методов:

  • public MailSenderClass(String user, String password) — Конструктор. В качестве аргументов передаются логин и пароль от нашего промежуточного ящика на gmail.com. Здесь же прописываются параметры smtp-подключения к серверу.
  • protected PasswordAuthentication getPasswordAuthentication() — Аутентификация для сервера.
  • public synchronized void sendMail(String subject, String body, String sender, String recipients, String filename) — Основной метод, в который передаются наши данные для отправки.

Рассмотрим код последнего метода чуть ближе:

  1. public synchronized void sendMail( String subject, String body, String sender, String recipients, String filename) throws Exception <
  2. try <
  3. MimeMessage message = new MimeMessage(session);
  4. // Кто
  5. message.setSender( new InternetAddress(sender));
  6. // О чем
  7. message.setSubject(subject);
  8. // Кому
  9. if (recipients.indexOf( ‘,’ ) > 0)
  10. message.setRecipients(Message.RecipientType.TO,
  11. InternetAddress.parse(recipients));
  12. else
  13. message.setRecipient(Message.RecipientType.TO,
  14. new InternetAddress(recipients));
  15. // Хочет сказать
  16. BodyPart messageBodyPart = new MimeBodyPart();
  17. messageBodyPart.setText(body);
  18. _multipart.addBodyPart(messageBodyPart);
  19. // И что показать
  20. if (!filename.equalsIgnoreCase( «» )) <
  21. BodyPart attachBodyPart = new MimeBodyPart();
  22. DataSource source = new FileDataSource(filename);
  23. attachBodyPart.setDataHandler( new DataHandler(source));
  24. attachBodyPart.setFileName(filename);
  25. _multipart.addBodyPart(attachBodyPart);
  26. >
  27. message.setContent(_multipart);
  28. Transport.send(message);
  29. > catch (Exception e) <
  30. Log.e( «sendMail» , «Ошибка отправки функцией sendMail! » );
  31. >
  32. >

* This source code was highlighted with Source Code Highlighter .

Метод также прост. Используя объект класса MimeMessage составляем наше письмо и для отправки передаём методу send, класса Transport.

JSSEProvider.java
Провайдер протокола безопасности для нашей почты. Линк.

VideoSelect.java
Код был взят из ApiDemos, которые поставляются в комплекте с Android SDK, и был чуть подправлен для выполнения с помощью метода startActivityForResult.
После выполнения возвращается строка, содержащая путь к файлу на карте памяти. Код можно будет посмотреть в проекте, он в конце статьи.

ExtendedMail.java
Основной метод отправления сообщения выполняется в функции sitv_sender_mail_async, представляющей класс AsyncTask:

  1. private class sender_mail_async extends AsyncTask String , Boolean><
  2. ProgressDialog WaitingDialog;
  3. @Override
  4. protected void onPreExecute() <
  5. // Выводим пользователю процесс загрузки
  6. WaitingDialog = ProgressDialog.show(ExtendedMail. this , «Отправка данных» , «Отправляем сообщение. » , true );
  7. >
  8. @Override
  9. protected void onPostExecute(Boolean result) <
  10. // Прячем процесс загрузки
  11. WaitingDialog.dismiss();
  12. Toast.makeText(mainContext, «Отправка завершена. » , Toast.LENGTH_LONG).show();
  13. ((Activity)mainContext).finish();
  14. >
  15. @Override
  16. protected Boolean doInBackground(Object. params ) <
  17. try <
  18. // Получаем данные с наших полей
  19. title = ((EditText)findViewById(R.id.screen_sendnews_et_title)).getText().toString();
  20. text = ((EditText)findViewById(R.id.screen_sendnews_et_text)).getText().toString();
  21. from = «from_post_msg@gmail.com» ;
  22. where = «where_post_msg@yandex.ru» ;
  23. // Вызываем конструктор и передаём в него наши логин и пароль от ящика на gmail.com
  24. MailSenderClass sender = new MailSenderClass( «mypostmail@gmail.com» , «password» );
  25. // И вызываем наш метод отправки
  26. sender.sendMail(title, text, from , where , attach);
  27. > catch (Exception e) <
  28. Toast.makeText(mainContext, «Ошибка отправки сообщения!» , Toast.LENGTH_SHORT).show();
  29. >
  30. return false ;
  31. >
  32. >

* This source code was highlighted with Source Code Highlighter .

  1. public void onClick(View v) <
  2. sender_mail_async async_sending = new sender_mail_async();
  3. async_sending.execute();
  4. >

* This source code was highlighted with Source Code Highlighter .

Таким образом создав небольшой класс-поток, можно спокойно слать необходимую информацию от клиента к себе на ящик.

Источник

Оцените статью