Last active
May 19, 2022 07:01
-
-
Save esabook/5256d658cdf8389cdc1efbada7022a5b to your computer and use it in GitHub Desktop.
Sample of sms listener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ***.services; | |
import android.content.BroadcastReceiver; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.os.Bundle; | |
import android.telephony.SmsMessage; | |
public class SmsBroadcastReceiver extends BroadcastReceiver { | |
private static SmsListener mListener; | |
public static String KNOWN_SENDER_ADDRESS = "esabook"; | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
// this function is trigged when each time a new SMS is received on device. | |
Bundle data = intent.getExtras(); | |
Object[] pdus = new Object[0]; | |
if (data != null) { | |
pdus = (Object[]) data.get("pdus"); // the pdus key will contain the newly received SMS | |
} | |
if (pdus != null) { | |
for (Object pdu : pdus) { // loop through and pick up the SMS of interest | |
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu); | |
// your custom logic to filter and extract the OTP from relevant SMS - with regex or any other way. | |
if (smsMessage.getOriginatingAddress().equals(KNOWN_SENDER_ADDRESS) && mListener != null) | |
mListener.onNewSmsReceived(smsMessage); | |
break; | |
} | |
} | |
} | |
public static void bindListener(SmsListener listener) { | |
mListener = listener; | |
} | |
public static void unbindListener() { | |
mListener = null; | |
} | |
public interface SmsListener { | |
void onNewSmsReceived(SmsMessage message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment