Listen For Incoming SMS Messages in Titanium Android app
Posted By : Sapna Sharma | 23-May-2016
Android applications having login via OTP functionality, reads incoming SMS messages to retrieve OTP from it and then fill it automatically. This is a nice feature the app providing nowadays. To achieve this feature in titanium mobile app, we would need to create a native module for that.
Here is the simple steps to create a titanium module that help us to listen Android messages.
Create a New Module
From terminal, change the current working directory to your workspace and run:
cd /path/to/workspace
appc new --n SmsListener --id com.oodles.smslistener -p Android
Develop the Module
Open the above created module in any available IDE(for eg Android Studio).
Add Permissions
Add following permissions in timodule.xml file :
For the Android devices running on Android 6.0, add following code inside SmsListenerModule.java to check whether SMS receive permission is enabled :
@Kroll.method
private boolean hasSMSReceivePermission() {
if (Build.VERSION.SDK_INT < 23) {
return true;
}
Activity currentActivity = TiApplication.getInstance().getCurrentActivity();
if (currentActivity.checkSelfPermission(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
hasSMSReceivePermission() returns true if permission is enabled otherwise return false.
Register Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. There are two ways to register a Broadcast Receivers :
-
A receiver can be registered via the AndroidManifest.xml file.
-
Alternatively to this static registration, you can also register a receiver dynamically via the Context.registerReceiver() method.
Here we are using static registration to register Broadcast Receivers.
If the event for which the broadcast receiver has registered happens, the onReceive() method of the receiver is called by the Android system. Add below code to register broadcast receivers, to listen for incoming message and to read SMS text.
void setupIntentReceivers() {
Activity currentActivity = TiApplication.getInstance().getCurrentActivity();
//let's register broadcast receivers
BroadcastReceiver smsReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Log.d(“SmsListenerModule”, "SMS Received");
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String message = currentMessage.getDisplayMessageBody();
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
}
}
} catch (Exception e) {
Log.e("SmsListenerModule", "An error occurred " + e);
}
break;
Default:
Log.d(“SmsListenerModule”, "SMS Receiving failure");
break;
}
}
};
Call the above method inside constructor as below given code :
public SmsListenerModule()
{
super();
setupIntentReceivers();
}
Build and Package the Module
To Build module compile it through ant. From a terminal, go to the module’s android directory and run ant :
cd /path/to/workspace/SmsListener/android
ant
Test the Module
After the build completes, find the module inside dist folder, unzip the built module and use it in test application.
Add the Module as a Dependency to the Project
com.oodles.smslistener
Load the Module and Make Module API Calls
Add below code in index.js file, which will make an API call to module.
var smslistener = require('com.oodles.smslistener');
//check whether SMS permissions are enabled
if (!smslistener.hasSMSReceivePermission()) {
//for android 6.0 move user to app settings to enable SMS permission at run time
var enablePermissionDialogue = Titanium.UI.createAlertDialog({
message : "To auto fetch OTP please enable SMS permission in the app's settings",
buttonNames : ['Allow', 'Deny'],
cancel : 1
});
enablePermissionDialogue.addEventListener('click', function(e) {
if (e.index === 0) {
var intent = Ti.Android.createIntent({
action : 'android.settings.APPLICATION_SETTINGS',
});
intent.addFlags(Ti.Android.FLAG_ACTIVITY_NEW_TASK);
Ti.Android.currentActivity.startActivity(intent);
}
});
enablePermissionDialogue.show();
return;
//listen SMS to auto fetch OTP
smslistener.addEventListener('complete', function(e) {
Ti.API.info('Result: ' + (e.success ? 'success' : 'failure') + ' msg: ' + e.resultMessage + 'sender' +e.senderNum);
switch (e.result) {
case smslistener.RECEIVED:
Ti.API.info("***********RECEIVED*********");
var arr = e.resultMessage.split(".");
var otp = (arr[0].split("is")[1]).trim();
break;
case smslistener.FAILED:
alert("Enter OTP manually");
break;
}
});
}
For module source code please go through below github link :
https://github.com/isapnasharma/Sapna-Oodles/tree/master/smsListener/android
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sapna Sharma
Sapna is a bright Android Apps developer using Titanium framework. Sapna likes music and helping needy people.