I need to implement a small text UI to show OTP MSM messages from inbox in Unity.
Does anyone know how to check or send SMS messages in Unity without opening the default SMS app?
I found the link below for sending the message without launching default SMS app. I want to read the SMS message in order to auto fill the OTP for the registration process. Is it possible with Unity?
https://gist.github.com/rmdwirizki/87f9e68c7ef6ef809a777eb25f12c3b2
On Android platform:
Demo Project here
Create an AAR plug-ins and Android Libraries. (You can either chose jar or aar to implement the plugin, the only difference is that aar plugin contains Android resources. In this case, we need to add permission into AndroidManifiest.xml which can be put inside aar and be merge by Unity automatically later)
Follow this instruction Create an Android library.
In the aar plugin, implement a BroadcastReceiver
that handles SMS receive intent.
SmsListener.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import com.unity3d.player.UnityPlayer;
public class SmsListener extends BroadcastReceiver {
private final String UnityCallbackObject = "UnitySMSReceiver";
private final String UnityCallbackMethod = "OnSMSReceive";
@Override
public void onReceive(Context context, Intent intent) {
StringBuilder builder = new StringBuilder();
Object[] objects = (Object[]) intent.getExtras().get("pdus");
SmsMessage message = null;
for (int i = 0; i < objects.length; i++) {
message = SmsMessage.createFromPdu((byte[]) objects[i]);
builder.append(message.getDisplayMessageBody());
}
UnityPlayer.UnitySendMessage(UnityCallbackObject, UnityCallbackMethod, builder.toString());
}
}
AndroidManifiest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name.here">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application>
<receiver android:name="your.package.name.here.SmsListener" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
In Unity side, put the generated aar file into Assets/Plugins/Android
.
Create an gameObject named UnitySMSReceiver
and attached a script implement function OnSMSReceive
in the scene.
public void OnSMSReceive (string message) {
// do something with your SMS message here.
}
My Environments:
Unity 2017.2.0f3
Android Studio 3.2.1
References:
Android testing sms from emulator
Android – Listen For Incoming SMS Messages
How can I read SMS messages programmatically in Android
Android: Programmatically receiving SMS messags
Android SMS Receiver not working
https://blog.gradle.org/introducing-compile-only-dependencies