Example usage for android.telephony SmsMessage getMessageBody

List of usage examples for android.telephony SmsMessage getMessageBody

Introduction

In this page you can find the example usage for android.telephony SmsMessage getMessageBody.

Prototype

public String getMessageBody() 

Source Link

Document

Returns the message body as a String, if it exists and is text based.

Usage

From source file:stream.messagingsample.SmsReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Object[] smsExtra = (Object[]) intent.getExtras().get("pdus");
    String body = "";

    for (int i = 0; i < smsExtra.length; ++i) {
        SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
        body += sms.getMessageBody();
    }/* w w  w.ja  va 2 s .c o  m*/

    Notification notification = new Notification.Builder(context).setContentText(body)
            .setContentTitle("New Message").setSmallIcon(stream.messagingsample.R.drawable.ic_alert)
            .setStyle(new Notification.BigTextStyle().bigText(body)).build();
    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
    notificationManagerCompat.notify(1, notification);
}

From source file:com.klinker.android.messaging_sample.SmsReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Object[] smsExtra = (Object[]) intent.getExtras().get("pdus");
    String body = "";

    for (int i = 0; i < smsExtra.length; ++i) {
        SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
        body += sms.getMessageBody();
    }/*from w ww .j  a v a2 s . c om*/

    Notification notification = new Notification.Builder(context).setContentText(body)
            .setContentTitle("New Message").setSmallIcon(R.drawable.ic_alert)
            .setStyle(new Notification.BigTextStyle().bigText(body)).build();
    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
    notificationManagerCompat.notify(1, notification);
}

From source file:com.example.hackinghealthclinification.app.ClinificationApp.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clinification_app);

    initializeLaunchButtons();//from w  ww  . j  a v  a  2s  .c  om
    mIsRegistered = false; // check if BroadcastReceiver registered
    IntentFilter filterSmsReceived = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");

    final SMSConfirmDialog.ConfirmDialogListener mListener = new SMSConfirmDialog.ConfirmDialogListener() {
        @Override
        public void onDialogPositiveClick(SMSConfirmDialog c) {
            //                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("yes"
            //                        + mPhoneNumber)));
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(mServerNumber, null, "yes", null, null);
        }

        @Override
        public void onDialogNegativeClick(SMSConfirmDialog c) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(mServerNumber, null, "no", null, null);
        }
    };

    mReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            mContext = context;
            Bundle pudsBundle = intent.getExtras();
            Object[] pdus = (Object[]) pudsBundle.get("pdus");
            SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
            Log.i("Error with SMS ::: ", messages.getMessageBody());
            if (messages.getMessageBody().contains(SMS_TRIGGER_KEY)) {
                mPhoneNumber = messages.getOriginatingAddress();
                SMSConfirmDialog dialog = new SMSConfirmDialog(mListener,
                        "Will you accept the new appointment: " + "\n" + messages.getMessageBody(), "Yes",
                        "No");
                dialog.show(getSupportFragmentManager(), null);
            }
        }
    };

    this.registerReceiver(mReceiver, filterSmsReceived);
    mIsRegistered = true;

}

From source file:com.xortech.sender.SmsReceiver.java

public void onReceive(final Context ctx, Intent intent) {
    // GET SMS MAP FROM INTENT
    Bundle extras = intent.getExtras();/*from  ww  w .j a va2s  .  c o m*/
    context = ctx;

    // GPS INSTANCE
    gps = new GPSTracker(context);

    // LOAD PREFERENCES
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    secretCode = preferences.getString("secretCode", DEFAULT_CODE);
    tagID = preferences.getString("tagID", DEFAULT_TAGID);
    senderEnabled = preferences.getBoolean("senderEnabled", true);

    if (extras != null) {

        // GET THE RECEIVED SMS ARRAY
        Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);

        for (int i = 0; i < smsExtra.length; ++i) {

            // GET THE MESSAGE
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);

            // PARSE THE MESSAGE BODY
            String body = sms.getMessageBody().toString();
            String address = sms.getOriginatingAddress();
            long time = System.currentTimeMillis();

            // GET COORDINATES AND SEND A MESSAGE
            gps.getLocation();

            latitude = String.valueOf(Math.round(FIVE_DIGIT * gps.getLatitude()) / FIVE_DIGIT);
            longitude = String.valueOf(Math.round(FIVE_DIGIT * gps.getLongitude()) / FIVE_DIGIT);
            location = "Tag_ID:" + tagID + ":Location:" + latitude + "," + longitude;
            googleString = GOOGLE_STRING + latitude + "," + longitude + "(" + tagID + ")";

            if (body.equals(SECRET_LOCATION_A + secretCode)) {
                if (senderEnabled) {
                    if (latitude.equals("0.0") | longitude.equals("0.0")) {
                        SmsManager.getDefault().sendTextMessage(address, null, NO_COORDS + tagID, null, null);
                    } else {
                        SmsManager.getDefault().sendTextMessage(address, null, googleString, null, null);
                    }
                }

                this.abortBroadcast();
            } else if (body.equals(SECRET_LOCATION_B + secretCode)) {
                if (senderEnabled) {
                    if (latitude.equals("0.0") | longitude.equals("0.0")) {
                        SmsManager.getDefault().sendTextMessage(address, null, NO_COORDS + tagID, null, null);
                    } else {
                        SmsManager.getDefault().sendTextMessage(address, null, location, null, null);
                    }
                }

                this.abortBroadcast();
            } else if (body.contains("Tag_ID:")) {
                // ADD TO DATABASE
                MsgDatabaseHandler dbHandler = new MsgDatabaseHandler(context);

                // VERIFY IF THE TAG EXISTS IN THE ARRAY
                String addressExists = VerifyTagExist(address);

                String[] splitBody = body.split(":");
                String tag = splitBody[1];
                tag.trim();
                String coords = splitBody[3];
                String[] splitCoords = coords.split(",");
                String lat = splitCoords[0];
                lat.trim();
                String lon = splitCoords[1];
                lon.trim();
                String _time = String.valueOf(time);
                String toastMsg = null;

                // CHECK IF THE ADDRESS EXISTS FOR NAMING PURPOSES
                if (addressExists == null) {
                    dbHandler.Add_Message(new MessageData(tag, address, lat, lon, _time));
                    toastMsg = "Response Received: " + tag;
                } else {
                    dbHandler.Add_Message(new MessageData(addressExists, address, lat, lon, _time));
                    toastMsg = "Response Received: " + addressExists;
                }

                dbHandler.close();

                Toast.makeText(context, toastMsg, Toast.LENGTH_LONG).show();

                this.abortBroadcast();
            } else if (body.contains("Panic!")) {

                // OVERRIDE THE SILENT FEATURE
                AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                int max = audio.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
                audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                audio.setStreamVolume(AudioManager.STREAM_RING, max,
                        AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

                // DEFINE THE NOTIFICATION MANAGER
                notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);

                // START A TIMER
                mytimer = new Timer(true);

                // SOUND LOCATION ALARM
                soundUri = Uri.parse(BEGIN_PATH + context.getPackageName() + FILE_PATH);

                // DISPLAY TAG ID FOR EMERGENCY
                String[] splitBody = body.split("\n");
                String fieldTag = splitBody[1];
                String[] splitTag = fieldTag.split(":");

                emergencyTag = splitTag[1].trim();

                // TIMER FOR NOTIFICATIONS
                mytask = new TimerTask() {
                    public void run() {
                        // RUN NOTIFICATION ON TIMER
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                                .setSmallIcon(R.drawable.emergency).setContentTitle(PANIC_TXT)
                                .setContentText(emergencyTag + UNDER_DURRESS).setSound(soundUri); //This sets the sound to play

                        // DISPLAY THE NOTIFICATION
                        notificationManager.notify(0, mBuilder.build());
                    }
                };
                // START TIMER AFTER 5 SECONDS
                mytimer.schedule(mytask, FIVE_SECONDS);
            }
        }
    }

    // CLEAR THE CACHE ON RECEIVING A MESSAGE
    try {
        MyUpdateReceiver.trimCache(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.androzic.plugin.tracker.SMSReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    String Sender = "";
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    Log.e(TAG, "SMS received");

    Bundle extras = intent.getExtras();// w  w  w. j  a v a2  s.c om
    if (extras == null)
        return;

    StringBuilder messageBuilder = new StringBuilder();
    Object[] pdus = (Object[]) extras.get("pdus");
    for (int i = 0; i < pdus.length; i++) {
        SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String text = msg.getMessageBody();
        Sender = msg.getDisplayOriginatingAddress();
        Log.w(TAG, "Sender: " + Sender);
        if (text == null)
            continue;
        messageBuilder.append(text);
    }

    String text = messageBuilder.toString();
    boolean flexMode = prefs.getBoolean(context.getString(R.string.pref_tracker_use_flex_mode),
            context.getResources().getBoolean(R.bool.def_flex_mode));

    Log.i(TAG, "SMS: " + text);
    Tracker tracker = new Tracker();
    if (!parseXexunTK102(text, tracker) && !parseJointechJT600(text, tracker)
            && !parseTK102Clone1(text, tracker) && !(parseFlexMode(text, tracker) && flexMode))
        return;

    if (tracker.message != null) {
        tracker.message = tracker.message.trim();
        if ("".equals(tracker.message))
            tracker.message = null;
    }

    tracker.sender = Sender;

    if (!"".equals(tracker.sender)) {
        // Save tracker data
        TrackerDataAccess dataAccess = new TrackerDataAccess(context);
        dataAccess.updateTracker(tracker);

        try {
            Application application = Application.getApplication();
            tracker = dataAccess.getTracker(tracker.sender);//get  latest positon of tracker

            application.sendTrackerOnMap(dataAccess, tracker);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dataAccess.close();

        context.sendBroadcast(new Intent(Application.TRACKER_DATE_RECEIVED_BROADCAST));

        // Show notification
        boolean notifications = prefs.getBoolean(context.getString(R.string.pref_tracker_notifications),
                context.getResources().getBoolean(R.bool.def_notifications));
        if (notifications) {
            Intent i = new Intent("com.androzic.COORDINATES_RECEIVED");
            i.putExtra("title", tracker.message != null ? tracker.message : tracker.name);
            i.putExtra("sender", tracker.name);
            i.putExtra("origin", context.getApplicationContext().getPackageName());
            i.putExtra("lat", tracker.latitude);
            i.putExtra("lon", tracker.longitude);

            String msg = context.getString(R.string.notif_text, tracker.name);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setContentTitle(context.getString(R.string.app_name));
            if (tracker.message != null)
                builder.setContentText(tracker.name + ": " + tracker.message);
            else
                builder.setContentText(msg);
            PendingIntent contentIntent = PendingIntent.getBroadcast(context, (int) tracker._id, i,
                    PendingIntent.FLAG_ONE_SHOT);
            builder.setContentIntent(contentIntent);
            builder.setSmallIcon(R.drawable.ic_stat_tracker);
            builder.setTicker(msg);
            builder.setWhen(tracker.time);
            int defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
            boolean vibrate = prefs.getBoolean(context.getString(R.string.pref_tracker_vibrate),
                    context.getResources().getBoolean(R.bool.def_vibrate));
            if (vibrate)
                defaults |= Notification.DEFAULT_VIBRATE;
            builder.setDefaults(defaults);
            builder.setAutoCancel(true);
            Notification notification = builder.build();
            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify((int) tracker._id, notification);
        }

        // Conceal SMS
        boolean concealsms = prefs.getBoolean(context.getString(R.string.pref_tracker_concealsms),
                context.getResources().getBoolean(R.bool.def_concealsms));
        if (concealsms)
            abortBroadcast();
    }
}

From source file:com.rjfun.cordova.sms.SMSPlugin.java

private JSONObject getJsonFromSmsMessage(SmsMessage sms) {
    JSONObject json = new JSONObject();

    try {/*from  ww  w .  ja  va  2  s . com*/
        json.put(ADDRESS, sms.getOriginatingAddress());
        json.put(BODY, sms.getMessageBody()); // May need sms.getMessageBody.toString()
        json.put(DATE_SENT, sms.getTimestampMillis());
        json.put(DATE, System.currentTimeMillis());
        json.put(READ, MESSAGE_IS_NOT_READ);
        json.put(SEEN, MESSAGE_IS_NOT_SEEN);
        json.put(STATUS, sms.getStatus());
        json.put(TYPE, MESSAGE_TYPE_INBOX);
        json.put(SERVICE_CENTER, sms.getServiceCenterAddress());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return json;
}

From source file:com.dileepindia.cordova.sms.SMSPlugin.java

private JSONObject getJsonFromSmsMessage(SmsMessage sms) {
    JSONObject json = new JSONObject();
    try {/*  w ww  . j a v a2  s.  c o m*/
        json.put("address", sms.getOriginatingAddress());
        json.put("body", sms.getMessageBody());
        json.put("date_sent", sms.getTimestampMillis());
        json.put("date", System.currentTimeMillis());
        json.put("read", 0);
        json.put("seen", 0);
        json.put("status", sms.getStatus());
        json.put("type", 1);
        json.put("service_center", sms.getServiceCenterAddress());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return json;
}

From source file:org.xwalk.runtime.extension.api.messaging.MessagingSmsManager.java

public void registerIntentFilters() {
    mSmsReceiveReceiver = new MessagingReceiver(mMessagingHandler) {
        @Override/*from   w ww  . j  a  v  a  2  s  .c o m*/
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();

            if (null == bundle) {
                return;
            }

            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; ++i) {
                try {
                    JSONObject jsonMsg = new JSONObject();
                    jsonMsg.put("cmd", "received");

                    SmsMessage msgs = SmsMessage.createFromPdu((byte[]) pdus[i]);

                    JSONObject jsData = new JSONObject();
                    jsonMsg.put("data", jsData);
                    JSONObject jsMsg = new JSONObject();
                    jsData.put("message", jsMsg);
                    jsMsg.put("messageID", "");
                    jsMsg.put("type", "sms");
                    jsMsg.put("serviceID", DEFAULT_SERVICE_ID);
                    jsMsg.put("from", msgs.getOriginatingAddress());
                    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    jsMsg.put("timestamp", sDateFormat.format(new java.util.Date()));
                    jsMsg.put("body", msgs.getMessageBody().toString());

                    mMessaging.broadcastMessage(jsonMsg.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    };

    mSmsSentReceiver = new MessagingReceiver(mMessagingHandler) {
        @Override
        public void onReceive(Context content, Intent intent) {
            boolean error = getResultCode() != Activity.RESULT_OK;
            String promise_id = intent.getStringExtra(EXTRA_MSGID);
            String smsMessage = intent.getStringExtra(EXTRA_MSGTEXT);
            String to = intent.getStringExtra(EXTRA_MSGTO);
            int instanceID = Integer.valueOf(intent.getStringExtra(EXTRA_MSGINSTANCEID));

            try {
                JSONObject jsSentMsg = new JSONObject();
                jsSentMsg.put("type", "sms");
                jsSentMsg.put("from", "");
                jsSentMsg.put("read", true);
                jsSentMsg.put("to", to);
                jsSentMsg.put("body", smsMessage);
                jsSentMsg.put("messageClass", "class1");
                jsSentMsg.put("state", "sending");
                jsSentMsg.put("deliveryStatus", error ? "error" : "pending");

                JSONObject jsonMsgPromise = new JSONObject();
                jsonMsgPromise.put("_promise_id", promise_id);
                jsonMsgPromise.put("cmd", "msg_smsSend_ret");
                JSONObject jsData = new JSONObject();
                jsonMsgPromise.put("data", jsData);
                jsData.put("error", error);
                jsData.put("body", jsSentMsg);

                mMessaging.postMessage(instanceID, jsonMsgPromise.toString());

                JSONObject jsonMsgEvent = new JSONObject();
                jsonMsgEvent.put("cmd", "sent");
                jsonMsgEvent.put("data", jsSentMsg);

                mMessaging.broadcastMessage(jsonMsgEvent.toString());
            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

            ContentValues values = new ContentValues();
            values.put("address", to);
            values.put("body", smsMessage);
            mMainActivity.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
        }
    };

    mSmsDeliveredReceiver = new MessagingReceiver(mMessagingHandler) {
        @Override
        public void onReceive(Context content, Intent intent) {
            boolean error = getResultCode() != Activity.RESULT_OK;
            String promise_id = intent.getStringExtra(EXTRA_MSGID);
            int instanceID = Integer.valueOf(intent.getStringExtra(EXTRA_MSGINSTANCEID));

            try {
                JSONObject jsonMsg = new JSONObject();
                jsonMsg.put("_promise_id", promise_id);
                jsonMsg.put("cmd", error ? "deliveryerror" : "deliverysuccess");
                JSONObject jsData = new JSONObject();
                jsonMsg.put("data", jsData);
                JSONObject jsEvent = new JSONObject();
                jsData.put("event", jsEvent);
                jsEvent.put("serviceID", DEFAULT_SERVICE_ID);
                jsEvent.put("messageID", "");
                jsEvent.put("recipients", "");
                SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                jsEvent.put("deliveryTimestamps", sDateFormat.format(new java.util.Date()));
                jsData.put("error", error);
                mMessaging.postMessage(instanceID, jsonMsg.toString());
            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }
        }
    };

    mSmsServiceReceiver = new MessagingReceiver(mMessagingHandler) {
        @Override
        public void onReceive(Context content, Intent intent) {
            try {
                JSONObject jsonMsg = new JSONObject();
                jsonMsg.put("cmd", checkService(DEFAULT_SERVICE_ID) ? "serviceadded" : "serviceremoved");
                JSONObject jsData = new JSONObject();
                jsonMsg.put("data", jsData);
                JSONObject jsEvent = new JSONObject();
                jsData.put("event", jsEvent);
                jsEvent.put("serviceID", DEFAULT_SERVICE_ID);
                mMessaging.broadcastMessage(jsonMsg.toString());
            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }
        }
    };

    mMainActivity.registerReceiver(mSmsReceiveReceiver,
            new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
    mMainActivity.registerReceiver(mSmsSentReceiver, new IntentFilter("SMS_SENT"));
    mMainActivity.registerReceiver(mSmsDeliveredReceiver, new IntentFilter("SMS_DELIVERED"));
    mMainActivity.registerReceiver(mSmsServiceReceiver,
            new IntentFilter("android.intent.action.SIM_STATE_CHANGED"));
}