Android get all messages

How to Receive and Handle SMS on Android

Despite the popularity of social media networks and messengers, texting is still the most common way to communicate via smartphones. According to the 2020 State of Texting report by Zipwhip, 77% of people use their texting app more frequently than other messengers.

But default SMS applications aren’t always comfortable for receiving SMS on Android, so users start looking for third-party apps. Additionally, non-messenger Android applications may still need SMS handling functionality (for example to confirm SMS authentication codes). In this article, we share our experience in developing SMS (and other service) handlers. In particular, we describe how to:

  • Make your application the default SMS handler
  • Develop an Android SMS receiver
  • Encrypt and decrypt SMS messages
  • Add texts to the SMS table in a device database

This text will be useful for developers who need to add SMS handling functionality to their app or create a new SMS messaging app.

Device Programming Team

Contents:

Making an app the default SMS handler

It’s important to make your application the default for handling SMS messages because only such app can record data to the SMS database. Your app should request permission to become the default SMS app before requesting any other permissions. This is also a requirement of the Google Play Store: if an app requests SMS, MMS, or CALL LOG permissions and isn’t a default SMS or Contact app, it will be rejected by Google.

In order to become the default messaging app, your app needs to:

  • Register a receiver to handle incoming SMS messages
  • Register a receiver to handle incoming MMS messages
  • Create an activity that allows users to send new SMS or MMS messages in the Android application
  • Create a service that sends out quick response messages

In our example, we’ll focus on how to receive SMS and send new SMS and MMS messages on Android. All of this functionality must be implemented in order to make our app the default handler.

We can use this code to ask a user to make our app the default for receiving SMS messages on Android:

In the code above, REQUEST_DEFAULT_APP is the request code to store the user’s choice. If the user allows the app to be the default, implementing this choice looks as follows:

Now we can proceed to the app manifest file and app permissions.

Developing the Android app manifest file

The app manifest file is a very important part of an Android application. It contains information on the app’s:

  • Package name
  • Components (activities, content providers, services, broadcast receivers)
  • Required permissions
  • Required software and hardware features

Let’s focus on the permissions for our application.

In Android 6, Google introduced runtime permissions. They protect the privacy of user data, tell users what information will be used by the app, and make sure users understand what an app can do with their data.

The runtime permissions system defines two permission levels:

  • Normal — Permissions to access data or resources that pose little to no risk to the user’s personal information (e.g. device time zone). These permissions don’t require the user’s approval.

Dangerous — Permissions to handle a user’s sensitive data (e.g. texts, messages, photos, notes, etc.). These require the user’s approval.

When an application requests permission, a system dialog appears. It contains a list of the permissions the app requires and Allow and Deny buttons.

Читайте также:  Как удалить android tv box

If the user denies a permission, when the app requests it the next time, the dialog box will contain a Do not ask me again checkbox.

When developing an app, you should take into account the scenario when a user denies permissions. All logic that relies on the denied permissions should not cause the app to fail.

In our example, the app’s manifest file declares permissions to read, send, and get all SMS in Android programmatically, as well as receive MMS messages, and receive push notifications:

After the declaration, the app should get the following permissions:

And handle the result of its requests in this way:

All of these permissions are in the same group, so they’re granted all together. If you request permissions from different permission groups, you’ll need to check the grantedResults array so you don’t miss any denied permissions.

To simplify the process of acquiring permissions, you can use a library like Quick Permissions.

Now it’s time to start a standard activity. In our example, this is part of an application that decrypts an SMS and shows it to the user. But in a real messaging app, there should also be an activity that provides functionality to create and send new SMS and MMS messages.

The part of our Manifest.xml file that describes our main activity looks like this:

Now we need to create an SMS receiver:

We also need to create an MMS receiver:

Finally, we should add a service that allows the user to respond to texts:

By this stage, our app can receive, display, and respond to texts. Let’s take a look at its ViewModel file.

Editing the ViewModel

At this stage, our project contains only one Extensible Markup Language (XML) layout. There’s one button and one list. The button is used for getting SMS messages from the system inbox; the list is used for showing messages.

Here’s the XML layout code:

And here’s a screenshot of our simple user interface:

As you can see, this XML doesn’t contain any listeners. We’ll add them later. Next, we need to introduce encryption and decryption algorithms.

Encrypting and decrypting SMS messages

All texts that our app receives will be encrypted. To handle them, we need to add a class that provides encryption and decryption.

In our application, encryption is done by executing the fun encrypt(data: String): String function. It encrypts a string with a key generated using the Password-Based Key Derivation Function (PBKDF2) algorithm. The returned value is an encrypted Base64 string.

Here’s what happens when we execute this function:

After that, we need to decrypt the SMS. To do that, we use the fun decrypt(encryptedData: String): String function. It decrypts the Base64 string with a PBKDF2 algorithm.

The decryption process looks like this:

To encrypt and decrypt the given ByteArray, we can use the fun cryptoOperation(cipherMode: Int, data: ByteArray): ByteArray function. We can execute it using the following code:

Encryption algorithms such as AES, Rivest–Shamir–Adleman, MD5, etc. require a secret key in the form of a ByteArray. We can generate a secret key that uses salt with the fun generateKey(): ByteArray function. Here’s an example of how to generate a key:

After executing these functions, our app can encrypt and decrypt texts. Now we can add an SMS handler.

Handling received SMS messages

The main class that receives SMS messages is SmsReceiver. It extends the BroadcastReceiver class. Any child class of BroadcastReceiver must contain the onReceive method, which receives Context and Intent parameters.

The BroadcastReceiver class is well-described in the official documentation, which is why we won’t focus on its properties.

When we get an event upon receiving a text, we need to go to the onReceive method. First, let’s confirm that all of the received content is valid:

The next step is to check that we’ve received the SMS data by checking the action value:

Now we’re ready to receive the SMS content with the val smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent) method. It will provide us an array of smsMessages. Here’s an example:

Читайте также:  Launcherapi android vshare com

When the SMS list gets into Intent, then the SMS should be parsed. For this purpose, we call the getMessagesFromIntent method from the Telephony.Sms.Intents class.

Then SmsReceiver gets the SMS and can do anything with it. In our example, SMS messages are encrypted and recorded in the SMS table of the device database. We need to do this to allow the default Android SMS viewer to view encrypted SMS messages.

When our app receives an SMS, it’s displayed using the Toast class.

Reading and decrypting SMS messages

After we’ve created encryption procedures, it’s time to add functionality for reading and decrypting SMS messages. Let’s list the click listener for the button on the main screen. All texts from the inbox are read, and then the sender information and SMS text are put into the list using this code:

The SMS is obtained from the list, decrypted, and then displayed to the user. The item listener list is as follows:

After that, our application is ready to handle SMS messages!

Conclusion

An application for handling text messages is must on any device. Lots of users aren’t satisfied with their default SMS app and are looking for a more comfortable solution. But there are several tricks to making an SMS app in Android Studio. It has to:

  • be the default application for SMS messages
  • ask for all necessary permissions (and not crash it a user denies them)
  • receive, display, and allow the user to respond to texts
  • be secure
  • add received texts to the device’s SMS database

In this article, we’ve shown you how to build an Android app with this functionality. Creating such applications is only the tip of the iceberg in terms of our experience in mobile app development. If you have a complex Android-related project, challenge us with it!

Источник

Read sms messages programatically in Android

by Anu S Pillai · Published March 4, 2017 · Updated March 20, 2017

Read SMS

In this tutorial we will see how to listen and read SMS programatically in Android. This feature is widely used in Apps to read OTPs and Secret Codes automatically without the need of the user to look and type the OTP manually.

Permissions

First lets add all the necessary permissions in Android Manifest which is required to listen to incoming SMS and read it. Copy – Paste the below code in your Manifest.

Register Broadcast Receiver in Manifest

Now lets register the broadcast receiver in the Android Manifest. Add below code inside the tag. We will create the SmsReceiver.java class shortly.

SmsListener Interface

Now lets create an Interface file SmsListener.java with the below code. This interface will help us notify the activity whenever a new SMS is received by the Broadcast receiver.

Broadcast Receiver

Now lets move on to create our Broadcast receiver which will listen to incoming sms. We have already registered the receiver in Manifest above. Create a Java file SmsReceiver.java and copy paste the below code in it.

Getting the Message in Activity

Lets create our MainActivity.java class in which we will receive the text and do some actions as per our requirements.

Please let me know your Suggestions / Queries in comments.

Follow GadgetSaint on Facebook / Twitter for updates.

Wanna start your blog or site in 5 mins? Check out Official WordPress recommended web hosting Bluehost.

The Admin at GadgetSaint.com

  • Next story Update : Fetch calories and steps using Google Fit API for any date
  • Previous story Create a Splash Screen with Video in Android

Fetch daily steps and calorie using Google Fit API

December 5, 2016

by Anu S Pillai · Published December 5, 2016 · Last modified March 31, 2017

Create a Simple Pedometer and Step Counter in Android

by Anu S Pillai · Published March 30, 2017 · Last modified July 6, 2019

Fetch active calories burned from Google Fit Android API

December 6, 2016

Читайте также:  Как сделать формат андроида

by Anu S Pillai · Published December 6, 2016 · Last modified March 31, 2017

9 Responses

I have tried to follow your example. However, I get the following errors:
Error:(7, 34) error: cannot find symbol class BroadcastReceiver
Error:(13, 27) error: cannot find symbol class Context
Error:(13, 44) error: cannot find symbol class Intent
Error:(12, 5) error: method does not override or implement a method from a supertype
Error:(14, 9) error: cannot find symbol class Bundle
Error:(19, 13) error: cannot find symbol class SmsMessage
Error:(19, 37) error: cannot find symbol variable SmsMessage

Any advice would be appreciated.

Hover @ the names and you will get the suggestions to import the files .
hope it will help you . 🙂

Nice Blog,but please give some more explanation of code to get understand

Источник

Полный список

— создаем более содержательные сообщения для Handler

В прошлых уроках мы использовали метод sendEmptyMessage. Этот метод сам создавал сообщение Message, заполнял его атрибут what и отправлял в очередь. Кроме what у сообщения есть еще атрибуты arg1 и arg2 типа int, и obj типа Object. В этом уроке мы сами будем создавать сообщение, заполнять атрибуты и отправлять.

Создадим приложение, которое будет подключаться к серверу, запрашивать кол-во файлов готовых для загрузки, эмулировать загрузку и отображать на экране ход действий, используя горизонтальный ProgressBar и TextView.

Project name: P0821_HandlerAdvMessage
Build Target: Android 2.3.3
Application name: HandlerAdvMessage
Package name: ru.startandroid.develop.p0821handleradvmessage
Create Activity: MainActivity

В onCreate мы создаем Handler и в его методе обработки (handleMessage) прописываем всю логику изменения экрана в зависимости от приходящих сообщений. Не буду подробно это расписывать, там все просто – меняем текст, включаем/выключаем кнопку, показываем/скрываем ProgressBar, меняем значение ProgressBar. Из интересного здесь стоит отметить, что читаем мы на этот раз не только what, но и остальные атрибуты сообщения – arg1, arg2, obj. А как они заполняются, увидим далее.

В onclick создаем новый поток для загрузки файлов. Устанавливаем подключение, получаем кол-во готовых для загрузки файлов. Если файлов для загрузки нет, посылаем соответствующее сообщение в Handler и отключаемся. Если же файлы есть, мы создаем сообщение Message с помощью метода obtainMessage (int what, int arg1, int arg2). Он принимает на вход атрибуты what, arg1 и arg2. В what мы кладем статус, в arg1 — кол-во файлов, arg2 – не нужен, там просто ноль.

Далее начинаем загрузку. После загрузки каждого файла мы создаем сообщение Message c помощью метода obtainMessage (int what, int arg1, int arg2, Object obj), заполняем его атрибуты: what – статус, arg1 – порядковый номер файла, arg2 – кол-во оставшихся файлов, obj – файл. И отправляем.

По завершению загрузки отправляем соответствующее сообщение и отключаемся.

downloadFile – эмулирует загрузку файла. ждет две секунды и возвращает массив из 1024 байтов.

saveFile – метод сохранения файла на диск. Просто заглушка. Ничего не делает.

Все сохраняем и запускаем. Жмем Connect.

Далее, либо начинается загрузка

либо появляется сообщение, что файлов нет

Используя разные атрибуты кроме what, мы смогли передать в основной поток и использовать там более разнообразные данные.

Мы создаем сообщения с помощью разных реализаций метода obtainMessage. А почему бы не создавать напрямую объект Message с помощью его конструкторов? В принципе можно, но официальный хелп рекомендует пользоваться методами obtainMessage, потому что это эффективней и быстрее. В этом случае сообщение достается из глобального пула сообщений, а не создается с нуля.

Здесь вы можете посмотреть все реализации метода obtainMessage для формирования сообщений и использовать тот, который подходит для ситуации. Они различаются разными комбинациями входных параметров.

На следующем уроке:

— посылаем отложенные сообщения
— удаляем сообщения из очереди
— используем Handler.Callback для обработки сообщений

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

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