Get code from sms android

Android: Обработка СМС

0. Вместо вступления

Периодически (когда у меня выпадает свободный вечер, и наш «клуб» организует игру) я играю в регбол. «Клуб» организован таким образом, что в день игры всем участникам приходит СМС такого вида:

Регбол! Сегодня в 19-30. Двор школы №30: ул. Володарского, 20. Открытая площадка с резиновым покрытием. Тел. 8 (951) ***-**-**.

И вот я подумал — почему бы не написать небольшое приложение, которое будет отлавливать эти сообщения, и забивать их в гугл-календарь. Зачем? Да, в основном, just for fun, ибо я не настолько занятой человек, чтобы мне были жизненно необходимы автоматические секретари.

Итак, приложение будет уметь следующее:

  • Следить за входящими сообщениями. Если пришло сообщение от адресата RM FIGHT, то нужно сверить текст сообщения с шаблоном, и при совпадении создать мероприятие в гугл-календаре. Если же текст сообщения с шаблоном не совпадает (например, просто какие-то новости пришли), то сохраняем сообщение в базе, чтобы потом можно было его прочитать.
  • Показывать сообщения от этого адресата, не попадающие в категорию «Оповещение об игре» (новости, реклама и т.д.).

В рамках статьи я полагаю, что у читателя есть базовые знания — как создать проект, что такое файл Manifest, и с чего вообще начинать разработку под андроид — на этот счет есть куча разных туториалов, и здесь на этом останавливаться не будем. В то же время статья не предназначена для продвинутых андроид-девелоперов, в ней будут рассматриваться достаточно базовые вещи, вроде мониторинга и обработки смс, работы с базой данных, подключения по HTTP.

Итак, приступим. Кстати, используемая версия SDK — 14 (Android 4.0).

1. Перехватываем СМС

Для мониторинга входящих СМС первым делом нам необходимо запросить разрешение на их получение. Для этого в файл AndroidManifest.xml необходимо добавить запись вида:

Следующим шагом будет реализация монитора для прослушивания входящих сообщений. Для этого в манифест-файле регистрируем receiver:

Здесь мы установили приоритет равным 100, чтобы наше приложение получило доступ к входящему СМС раньше стандартного обработчика СМС, которое имеет нулевой приоритет. После того, как наше приложение обработает сообщение, нет смысла отдавать его системе, и помещать в папку Входящие.

Теперь создаем класс, расширяющий BroadcastReceiver :

В этом классе реализуется абстрактный метод onReceive() , который вызывается системой каждый раз при получении сообщения. В методе прописываем:

Здесь мы получаем сообщение с помощью метода intent.getExtras().get(«pdus») , который возвращает массив объектов в формате PDU — эти объекты мы потом приводим к типу SmsMessage с помощью метода createFromPdu() .

Теперь внимание. То, что мы делаем после получения сообщения, должно исполняться быстро. Broadcast receiver получает в системе высокий приоритет, но он работает в фоновом режиме и должен выполняться за короткое время, так что наши возможности ограничены. Например, мы можем сгенерировать уведомление или запустить службу, чтобы продолжить обработку в ней. Поэтому мы проверим отправителя сообщения, и если это уведомление об игре — мы вытащим текст сообщения и запустим службу, в которой уже и будем проводить обработку этого сообщения.

Дописываем в методе onReceive() :

Здесь мы составляем текст сообщения (в случае, когда сообщение было длинным и пришло в нескольких смс-ках, каждая отдельная часть хранится в messages[i] ) и вызываем метод abortBroadcast() , чтобы предотвратить дальнейшую обработку сообщения другими приложениями.

2. Обрабатываем СМС

В предыдущем пункте мы остановились на том, что запускаем службу для обработки смс с помощью метода startService() . Собственно, что такое службы и с чем их едят хорошо описано на официальном сайте, поэтому здесь на этом останавливаться не будем.

Читайте также:  Все версии ватсап для андроида

Создаем класс SmsService , расширяющий класс Service :

Поскольку у нас локальная служба, метод onBind() возвращает null.

Для вывода уведомлений нам понадобится вспомогательный метод showNotification():

В методе onStartCommand() прописываем:

Осталось, собственно, реализовать метод smsProcess() , который добавит смс в базу и сформирует мероприятие в гугл-календаре. Этим и займемся в следующей части статьи.

UPDATE: выложил код на GitHub. Со второй частью статьи пока не успеваю, слишком уж загружен по работе. Надеюсь в ближайшее время с этим вопросом разберусь.

Источник

Android automatic SMS verification — Google’s SMS retriever API

As time passes android is getting better in all means for example security, from Android M google has provided the users to have control over permissions like Read SMS, Storage, Contacts, etc. Now Google allows only one app at a time to read and manage your messages i.e only your default messenger app of your choice(I think it was the most necessary step).
As Google is preventing apps to read SMS it has introduced SMS Retriever API to give access to the messages received from there servers to continue with tasks like Autofill OTP, e.t.c.

Message Format

Before getting into action you should know the new format of OTP messages introduced by Google. Have a look at the format

By a glance at the format, you might have an idea. let me explain it briefly,
there two conditions we should follow

  1. The message should start with , that will indicate this is an OTP message to the system.
  2. The message should end with Hashcode generated using command prompt or AppSignatureHelper class, Based on this hashcode system will pass the message to the respective app. how to generate hashcode will be explained in the following steps.

The image below represents how SMS Retriever API works

Источник

Automatic SMS verification with SMS retriever API in Android

Nowadays, SMS verification is the best way that is being used by mobile applications for login purpose. There are many ways to automatically fill the OTP field by reading the message in our phone using READ_SMS permission. But, Google has strictly prohibited the usage of that permission for security purposes. You can read the full explanation here.

Since we can’t use the READ_SMS permission anymore, Google has given some other choices to implement automatic SMS verification using SMS Retriever API. With the SMS Retriever API, we can perform SMS-based user verification in our Android app automatically, without requiring the user to manually type verification codes, and without requiring any extra app permissions

* No need any sms permission for sms retriever api

In this article, we will learn our SMS Retriever API and see how this can be easily used for SMS verification. So, let’s get started.

Prerequisites

The SMS Retriever API is available only on Android devices with Play services version 10.2 and newer.

Step 01

Add the dependency in-app level Gradle file:

Step 02

Create SMS Broadcast Receiver to receive the message:

When a client’s phone receives any message containing a unique string, SMS Retriever API will broadcast the message with SmsRetriever.SMS_RETRIEVED_ACTION intent. Then, we should use a broadcast receiver to receive the verification message. In the BroadcastReceiver ‘s onReceive handler, we will get the text of the verification message from the Intent’s extras, then extract the verification code with regular expression:

Step 03

Init & Register the SMS Broadcast Receiver:

  • Init this BroadcastReceiver with the intent filter SmsRetriever.SMS_RETRIEVED_ACTION in onCreate()
  • Register the receiver in onResume()
  • Unregister the receiver in onPause()

Start Sms Retriver API in onCreate()

Full MainActivity class looks like this:

Our coding is done! Now its time to construct the message.

** Construct Verification Message

Yes SMS retriever API doesn’t require any permission, but you have to make sure that the message follow these criteria:

  • Be no longer than 140 bytes
  • Contain a one-time code
  • End with an 11-character hash string that identifies your app

Computing your app’s hash string

Google Play services uses the hash string to determine which verification messages to send to your app. The hash string is made of your app’s package name and your app’s public key certificate. To generate the hash string:

Читайте также:  Код для системного меню андроида

Let’s create a class named is AppSignatureHelper and paste the below code. This is the simplest way to get hash string. You can generate using CMD as well. Once you got hash string then that deletes helper class.

However, if you use the helper class, be sure to remove it from your app after you get the hash string. Do not use hash strings dynamically computed on the client in your verification messages.

Send the verification message by SMS

After you construct the verification message, send the message to the user’s phone number using any SMS system.

** Things you must do **

  • Once you completed get the hash code to remove the AppSignatureHelper class from your project before going to live or production.
  • In Android, Debug and Release APK’s have different hash string, Kindly make sure you get hash code from release build.

Be sure to give claps if you find something useful from this article. Find the source code from GitHub here.

Источник

Get code from sms android

SMS Parser — Android

Receiving and Parsing SMS Messages on Android Devices

This module was created for getting specific codes out of incoming SMS messages. To use it you create a Config object where you specify the BEGIN and END message phrases & the SMS sender numbers from which you want to read the sms content. The received code then can be used according to your need (activation, authentication etc. ).

If you get a SMS message like this:

and the sender of the message is one of the numbers you have specified in your Config object the parsing process will begin.

First the module reads the whole message. It then checks if it contains the BEGIN and END phrases you specified. If it does then it takes only the part that is between those phrases and send a broadcast to you app with the specific code and the sender phone number. In this case the module would send a broadcast containing 08ff08d3b2981eb6c611a385ffa4f865 and the sender number.

For more info read Usage.

Add the module to your apps build.gradle:

First of all you have to create a Config object to configure the modules use:

Here the two parameters are the keywords that will be used for the code to be extracted from the sms message. The third parameter is a varargs (. ) parameter, where you can give a series of phone numbers (as Strings), which will be checked against for reading sms content.

Then before startinganything you have to aks for the SMS Permmision on Android 6.0 and higher, or else the module won’t work:

Then you need to create a LocalBroadcastManager and BroadcastReceiver, like this:

LocalBroadcastManager is used instead of standard BroadcastManager for security reasons, so no other app can listen to the broadcasts that are sent.

You must create register and unregister methods for the BroadcastReceiver and call them in onResume() and onPause(), respectively:

Источник

Automatic SMS Verification Android

In this post, I’m going to show you how to implement automatic SMS verification with SMS Retriever API. Using SMS Retriever API you can perform SMS verification in your app automatically, without requiring extra permission.

Table of Contents

  • Automatic SMS Verification Demo App
  • Introduction
  • Why you should use SMS Retriever API
  • Understand the SMS verification process
  • Step of ImplementationAdd gradle dependency in-app level
  • Retrieve user’s content from the Phone
  • Start SMS Retriever
  • Create an SMS Broadcast Receiver
  • Register SMS broadcast receiver in AndroidManifest
  • Initiate the request for OTP
  • Get SMS format & verification code in SMS Broadcast Receiver
  • Test the Demo App
  • Things you must do
  • Technology Used
  • Conclusion

1. Automatic SMS Verification Demo App

2. Introduction

I shared step by step process to implement automatic SMS verification in your Android App. Before that, Let’s understand the flow of SMS verification process.

The above figure gives you little bit clarity on SMS verification.

3. Why you should use SMS Retriever API

Google change some critical changes in policy. From Jan 19th, 2019 google removed all app from play store with permission CALL_LOG and READ_SMS

Читайте также:  Установить opengl для андроида

4. Understand the SMS verification process

Earlier, when user had to login in android app on Android Platform, They enter mobile number to receive OTP. Then they gives READ_SMS permission to app for reading SMS. Recently Google had made some important change in its policy. Now Android Platform removes this permission due to data security reasons. So now you have to copy code received through SMS. Go back to the app and enter that code manually to log in.

For overcoming this process, Google introduced SMS Retriever API to automatically fetch a verification code sent via SMS within the app. This way, user was not required to manually enter the code every time. Let’s follow the these given step to implement Automatic SMS Verification in an Android App.

5. Step of Implementation

Now, I will explain you step by step process to implement automatic SMS verification in your Android App

5.1 Add gradle dependency in-app level

Add the below lib in app level build.gradle for integrating SMS Retriever API in your project

5.2 Retrieve user’s content from the Phone

Obtain the phone number from device through hint picker for do that follow below step

  • Setup Google API Client
  • Get an available number in user phone
  • Get Selected Number in onActivityResult
5.3 Start SMS Retriever

Once user submitted the phone, we should initiate SMS retrieval task

5.4 Create an SMS Broadcast Receiver

Let’s create a Broadcast Receiver to receive SMS from SMS retriever API

Create a listener that send the OTP to activity or fragment
5.6 Register SMS broadcast receiver in AndroidManifest

Open the Android Manifest and register the receiver with intent filter

5.7 Open activity_main.xml and paste below code
5.8 Initiate the request for OTP

Call server API for requesting OTP and when you got success start SMS Listener for listing auto read message listener

5.9 Get SMS format & verification code in SMS Broadcast Receiver

This receiver will receive the OTP and pass to the activity where you can finish authentication.

The full source code of MainActivity.java

6. Test the Demo App

When sever receive the request to OTP via REST API, Server will send OTP message to device. You have to follow below message format.

Message Format Must Be –

Google introduced a new format for OTP message. Follow below SMS format

  • Prefix:
    • The message should start with
  • Content: Your OTP is: 156367
  • Postfix: Application key hash from Keystore (Debug or Release) eg. T61bL03HCN8
    • The message should end with hashcode. It received from LOG CAT generated by the AppSignature helper. Based on this system will pass the message to the respective app.
Let’s check below Example

You OTP is: 156367 T61bL03HCN8

For server side code you can follow below link

7. How to get APK’s hashcode for SMS construction

Let’s create a class named is AppSignatureHelper and paste the below code. This is the simplest way to get Hashcode. You can generate using CMD as well. Once you got hashcode than that deletes helper class.

Call getAppSignatures() methods in application onCreate()

8. Things you must do

  • Once you completed get the hash code to remove the AppSignatureHelper class from your project before going to live or production.
  • In Android, Debug and Release APK’s have different Hashcode, Kindly make sure you get hash code from release build.

9. Technology Used

Tool: Android Studio v3.3 with API 28 (Pie 9.0), SDK
Language: Java, XML

Conclusion

With the help of this android app tutorial, We have learned how to implement automatic SMS verification using SMS Retriever API. Later I will upload APK and Source code as well, So you can get source of this demo app.

Get Solution Code

If you have any comments and queries please put your comment below. If you looking to integrate the automatic SMS verification process in your android project, Feel free to content us.

Источник

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