Using BroadcastReceiver, allows the system to get alert whenever a message received. Upon message reception, you can handle as per requirement. A message may be composed of multi-parts, so, you can combine it and show as a single complete message. Following is the onReceive method:
@Override
public void onReceive(Context context, Intent intent) {
// Get the data (SMS data) bound to intent StringBuilder text=new StringBuilder(); // Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras(); Log.d(TAG, "onReceive"); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); for (int parts = 0; parts < pdusObj.length; parts++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[parts]);
String senderNumber = currentMessage.getDisplayOriginatingAddress(); String message = currentMessage.getDisplayMessageBody(); Log.i("SmsReceiver", "senderNumber: "+ senderNumber + "; message: " + message); text.append(message); //combine sms parts as a single message } // end for loop // Show Alert
Toast.makeText(context, "Complete Message: " +text.toString() , Toast.LENGTH_LONG).show(); } // bundle is null } catch (Exception e) { Log.e("SmsReceiver", "Exception smsReceiver" +e); } }
No comments:
Post a Comment