Example usage for android.telephony SmsMessage getOriginatingAddress

List of usage examples for android.telephony SmsMessage getOriginatingAddress

Introduction

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

Prototype

@Nullable
public String getOriginatingAddress() 

Source Link

Document

Returns the originating address (sender) of this SMS message in String form or null if unavailable.

Usage

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();/*w ww.  ja va  2 s. 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();/*  w  w  w  .ja v a  2s  .  c  om*/
    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.rjfun.cordova.sms.SMSPlugin.java

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

    try {//from ww  w  .  j  a  v a  2  s .c  om
        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 a  2  s .  c  om*/
        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   ww w.  j  ava 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"));
}