Last active
June 17, 2021 11:32
-
-
Save chathudan/127b7b3715687328d95e to your computer and use it in GitHub Desktop.
Android SMS Receive Listener
This file contains 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
import android.content.BroadcastReceiver; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.os.Bundle; | |
import android.telephony.SmsMessage; | |
import java.util.ArrayList; | |
/** | |
* @@author Chathura Wijesinghe <[email protected]> | |
* | |
* <receiver android:name=".SMSReceiver" > | |
<intent-filter> | |
<action android:name="android.provider.Telephony.SMS_RECEIVED"/> | |
</intent-filter> | |
</receiver> | |
*/ | |
public class SMSReceiver extends BroadcastReceiver { | |
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; | |
private static ArrayList<SMSReceivedListner> smsListner = new ArrayList<SMSReceivedListner>(); | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
final String action = intent.getAction(); | |
final Bundle extras = intent.getExtras(); | |
if (action.equals(SMSReceiver.SMS_RECEIVED)) { | |
final boolean smsValid = extras != null; | |
if (smsValid) { | |
//Create SMSMessages from PDUs in the Bundle | |
final Object[] pdus = (Object[])extras.get("pdus"); | |
final SmsMessage[] messages = new SmsMessage[pdus.length]; | |
for (int i = 0; i < pdus.length; i++) | |
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]); | |
//Assemble | |
final ArrayList<Long> vibrations = new ArrayList<Long>(); | |
for (SmsMessage message : messages) { | |
for (SMSReceivedListner smsReceivedListner : smsListner ) | |
smsReceivedListner.message(message); | |
} | |
} | |
} | |
} | |
public static void addSMSListner(SMSReceivedListner listner){ | |
smsListner.add(listner); | |
} | |
public static void removeSMSListner(SMSReceivedListner listner){ | |
smsListner.remove(listner); | |
} | |
public interface SMSReceivedListner{ | |
public void message(SmsMessage message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you call this class to the main activity?