Sending message in android studio

Android — Sending SMS

In Android, you can use SmsManager API or devices Built-in SMS application to send SMS’s. In this tutorial, we shows you two basic examples to send SMS message −

Built-in SMS application

Of course, both need SEND_SMS permission.

Apart from the above method, there are few other important functions available in SmsManager class. These methods are listed below −

ArrayList divideMessage(String text)

This method divides a message text into several fragments, none bigger than the maximum SMS message size.

static SmsManager getDefault()

This method is used to get the default instance of the SmsManager

void sendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)

This method is used to send a data based SMS to a specific application port.

void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList parts, ArrayList

Send a multi-part text based SMS.

void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)

Send a text based SMS.

Example

Following example shows you in practical how to use SmsManager object to send an SMS to the given mobile number.

To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.

Sr.No. Method & Description
1
Step Description
1 You will use Android Studio IDE to create an Android application and name it as tutorialspoint under a package com.example.tutorialspoint.
2 Modify src/MainActivity.java file and add required code to take care of sending sms.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple GUI to take mobile number and SMS text to be sent and a simple button to send SMS.
4 No need to define default string constants at res/values/strings.xml. Android studio takes care of default constants.
5 Modify AndroidManifest.xml as shown below
6 Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/com.example.tutorialspoint/MainActivity.java.

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo

Following will be the content of res/values/strings.xml to define two new constants −

Following is the default content of AndroidManifest.xml

Let’s try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.

Now you can enter a desired mobile number and a text message to be sent on that number. Finally click on Send SMS button to send your SMS. Make sure your GSM/CDMA connection is working fine to deliver your SMS to its recipient.

You can take a number of SMS separated by comma and then inside your program you will have to parse them into an array string and finally you can use a loop to send message to all the given numbers. That’s how you can write your own SMS client. Next section will show you how to use existing SMS client to send SMS.

Using Built-in Intent to send SMS

You can use Android Intent to send SMS by calling built-in SMS functionality of the Android. Following section explains different parts of our Intent object required to send an SMS.

Intent Object — Action to send SMS

You will use ACTION_VIEW action to launch an SMS client installed on your Android device. Following is simple syntax to create an intent with ACTION_VIEW action.

Intent Object — Data/Type to send SMS

To send an SMS you need to specify smsto: as URI using setData() method and data type will be to vnd.android-dir/mms-sms using setType() method as follows −

Intent Object — Extra to send SMS

Android has built-in support to add phone number and text message to send an SMS as follows −

Here address and sms_body are case sensitive and should be specified in small characters only. You can specify more than one number in single string but separated by semi-colon (;).

Example

Following example shows you in practical how to use Intent object to launch SMS client to send an SMS to the given recipients.

To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.

Step Description
1 You will use Android studio IDE to create an Android application and name it as tutorialspoint under a package com.example.tutorialspoint.
2 Modify src/MainActivity.java file and add required code to take care of sending SMS.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple button to launch SMS Client.
4 No need to define default constants.Android studio takes care of default constants.
5 Modify AndroidManifest.xml as shown below
6 Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/com.example.tutorialspoint/MainActivity.java.

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo

Following will be the content of res/values/strings.xml to define two new constants −

Following is the default content of AndroidManifest.xml

Let’s try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which will display following screen −

Now use Compose SMS button to launch Android built-in SMS clients which is shown below −

You can modify either of the given default fields and finally use send SMS button to send your SMS to the mentioned recipient.

Источник

2.2: Part 2 — Sending and Receiving SMS Messages

Contents:

Task 3. Receive SMS messages with a broadcast receiver

To receive SMS messages, use the onReceive() method of the BroadcastReceiver class. The Android framework sends out system broadcasts of events such as receiving an SMS message, containing intents that are meant to be received using a BroadcastReceiver. You need to add the RECEIVE_SMS permission to your app’s AndroidManifest.xml file.

3.1 Add permission and create a broadcast receiver

To add RECEIVE_SMS permission and create a broadcast receiver, follow these steps:

Open the AndroidManifest.xml file and add the android.permission.RECEIVE_SMS permission below the other permission for SMS use:

Receiving an SMS message is permission-protected. Your app can’t receive SMS messages without the RECEIVE_SMS permission line in AndroidManifest.xml.

Name the class «MySmsReceiver» and make sure «Exported» and «Enabled» are checked.

The «Exported» option allows your app to respond to outside broadcasts, while «Enabled» allows it to be instantiated by the system.

  • Open the AndroidManifest.xml file again. Note that Android Studio automatically generates a tag with your chosen options as attributes:
  • 3.2 Register the broadcast receiver

    In order to receive any broadcasts, you must register for specific broadcast intents. In the Intent documentation, under «Standard Broadcast Actions», you can find some of the common broadcast intents sent by the system. In this app, you use the android.provider.Telephony.SMS_RECEIVED intent.

    Add the following inside the tags to register your receiver:

    3.3 Implement the onReceive() method

    Once the BroadcastReceiver intercepts a broadcast for which it is registered ( SMS_RECEIVED ), the intent is delivered to the receiver’s onReceive() method, along with the context in which the receiver is running.

    1. Open MySmsReceiver and add under the class declaration a string constant TAG for log messages and a string constant pdu_type for identifying PDUs in a bundle:
    2. Delete the default implementation inside the supplied onReceive() method.

    In the blank onReceive() method:

    Add the @TargetAPI annotation for the method, because it performs a different action depending on the build version.

    Retrieve a map of extended data from the intent to a bundle .

    Define the msgs array and strMessage string.

    Get the format for the message from the bundle .

    As you enter SmsMessage[] , Android Studio automatically imports android.telephony.SmsMessage .

    Initialize the msgs array, and use its length in the for loop:

    Use createFromPdu(byte[] pdu, String format) to fill the msgs array for Android version 6.0 (Marshmallow) and newer versions. For earlier versions of Android, use the deprecated signature createFromPdu(byte[] pdu).

    Build the strMessage to show in a toast message:

    Get the originating address using the getOriginatingAddress() method.

    Get the message body using the getMessageBody() method.

    Add an ending character for an end-of-line.

  • Log the resulting strMessage and display a toast with it:
  • The complete onReceive() method is shown below:

    3.4 Run the app and send a message

    Run the app on a device. If possible, have someone send you an SMS message from a different device.

    You can also receive an SMS text message when testing on an emulator. Follow these steps:

      Run the app on an emulator.

    Click the (More) icon at the bottom of the emulator’s toolbar on the right side, as shown in the figure below:

  • The extended controls for the emulator appear. Click Phone in the left column to see the extended phone controls:
  • You can now enter a message (or use the default «marshmallows» message) and click Send Message to have the emulator send an SMS message to itself.
  • The emulator responds with a notification about receiving an SMS message. The app should also display a toast message showing the message and its originating address, as shown below:
  • Solution Code

    Android Studio project: SmsMessaging

    Coding challenge

    Challenge: Create a simple app with one button, Choose Picture and Send, that enables the user to select an image from the Gallery and send it as a Multimedia Messaging Service (MMS) message. After tapping the button, a choice of apps may appear, including the Messenger app. The user can select the Messenger app, and select an existing conversation or create a new conversation, and then send the image as a message.

    The following are hints:

    • To access and share an image from the Gallery, you need the following permission in the AndroidManifest.xml file:
    • To enable the above permission, follow the model shown previously in this chapter to check for the READ_EXTERNAL_STORAGE permission, and request permission if necessary.
    • Use the following intent for picking an image:
    • Override the onActivityResult method to retrieve the intent result, and use getData() to get the Uri of the image in the result:
    • Set the image’s Uri, and use an intent with ACTION_SEND , putExtra() , and setType() :
    • Android Studio emulators can’t pass MMS messages to and from each other. You must test this app on real Android devices.
    • For more information about sending multimedia messages, see Sending MMS with Android.

    Android Studio project: MMSChallenge

    Источник

    Отправка 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 .

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

    Источник

    Читайте также:  Просмотра документов для android
    Оцените статью