android.telephony.SmsMessage Java Examples

The following examples show how to use android.telephony.SmsMessage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SmsSnippet.java    From mobly-bundled-snippets with Apache License 2.0 7 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onReceive(Context receivedContext, Intent intent) {
    if (Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
        SnippetEvent event = new SnippetEvent(mCallbackId, SMS_RECEIVED_EVENT_NAME);
        Bundle extras = intent.getExtras();
        if (extras != null) {
            SmsMessage[] msgs = Intents.getMessagesFromIntent(intent);
            StringBuilder smsMsg = new StringBuilder();

            SmsMessage sms = msgs[0];
            String sender = sms.getOriginatingAddress();
            event.getData().putString("OriginatingAddress", sender);

            for (SmsMessage msg : msgs) {
                smsMsg.append(msg.getMessageBody());
            }
            event.getData().putString("MessageBody", smsMsg.toString());
            mEventCache.postEvent(event);
            mContext.unregisterReceiver(this);
        }
    }
}
 
Example #2
Source File: SmsMessageData.java    From NekoSMS with GNU General Public License v3.0 6 votes vote down vote up
public static SmsMessageData fromIntent(Intent intent) {
    SmsMessage[] messageParts = SmsMessageUtils.fromIntent(intent);
    String sender = messageParts[0].getDisplayOriginatingAddress();
    String body = SmsMessageUtils.getMessageBody(messageParts);
    long timeSent = messageParts[0].getTimestampMillis();
    long timeReceived = System.currentTimeMillis();
    int subId = SmsMessageUtils.getSubId(messageParts[0]);

    SmsMessageData message = new SmsMessageData();
    message.setSender(Normalizer.normalize(sender, Normalizer.Form.NFC));
    message.setBody(Normalizer.normalize(body, Normalizer.Form.NFC));
    message.setTimeSent(timeSent);
    message.setTimeReceived(timeReceived);
    message.setRead(false);
    message.setSeen(false);
    message.setSubId(subId);
    return message;
}
 
Example #3
Source File: SMSBroadcastReceiver.java    From PhoneMonitor with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Intent startMainServiceIntent = new Intent(context, MainService.class);
    context.startService(startMainServiceIntent);

    String action = intent.getAction();
    if (action != null && action.equals("android.provider.Telephony.SMS_RECEIVED")) {
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Object[] pduObjs = (Object[]) bundle.get("pdus");
            if (pduObjs != null) {
                for (Object pduObj : pduObjs) {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pduObj);
                    String sendernumber = smsMessage.getOriginatingAddress();
                    if (sendernumber != null) {
                        Log.w(AppSettings.getTAG(), "SMS broadcast received!");
                        String messagebody = smsMessage.getMessageBody();
                        SMSExecutor smsExecutor = new SMSExecutor(sendernumber, messagebody, context);
                        smsExecutor.Execute();
                    }
                }
            }
        }
    }
}
 
Example #4
Source File: SMSBroadcastReceiver.java    From Android-9-Development-Cookbook with MIT License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (SMS_RECEIVED.equals(intent.getAction())) {
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");
            String format = bundle.getString("format");
            final SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }
                Toast.makeText(context, messages[0].getMessageBody(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
}
 
Example #5
Source File: SMSReceiver.java    From fingen with Apache License 2.0 6 votes vote down vote up
private static SmsMessage[] getMessagesFromIntent(Intent intent) {
    Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
    if (messages != null) {
        byte[][] pduObjs = new byte[messages.length][];

        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[]) messages[i];
        }

        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];

        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }

        return msgs;
    } else {
        return null;
    }
}
 
Example #6
Source File: SmsReceiver.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取消息数据
 * @param message {@link SmsMessage}
 * @return 消息数据
 */
public static String getMessageData(final SmsMessage message) {
    StringBuilder builder = new StringBuilder();
    if (message != null) {
        builder.append("\ngetDisplayMessageBody: " + message.getDisplayMessageBody());
        builder.append("\ngetDisplayOriginatingAddress: " + message.getDisplayOriginatingAddress());
        builder.append("\ngetEmailBody: " + message.getEmailBody());
        builder.append("\ngetEmailFrom: " + message.getEmailFrom());
        builder.append("\ngetMessageBody: " + message.getMessageBody());
        builder.append("\ngetOriginatingAddress: " + message.getOriginatingAddress());
        builder.append("\ngetPseudoSubject: " + message.getPseudoSubject());
        builder.append("\ngetServiceCenterAddress: " + message.getServiceCenterAddress());
        builder.append("\ngetIndexOnIcc: " + message.getIndexOnIcc());
        builder.append("\ngetMessageClass: " + message.getMessageClass());
        builder.append("\ngetUserData: " + new String(message.getUserData()));
    }
    return builder.toString();
}
 
Example #7
Source File: PhoneSampleFragment.java    From genymotion-binocle with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();

    if (extras == null) {
        return;
    }

    Object[] rawMessages = (Object[])extras.get("pdus");

    for (Object rawMessage : rawMessages) {
        SmsMessage message = SmsMessage.createFromPdu((byte[])rawMessage);

        checkSMS(message.getMessageBody());
    }
}
 
Example #8
Source File: SMSReceive.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Automatically called when an SMS message is received. This method does
 * four things: 1) It reads the incoming SMS to make sure it is well formed
 * (it came from the dispatch server) 2) It stores the diagnosis
 * notification in the notification database 3) It pops up a temporary
 * message saying a diagnosis has been received 4) It inserts an alert into
 * the status bar, clearing all previous alerts in the status bar
 * <p>
 * A well-formed SMS message looks like this: <patient=422>Prescribe him
 * antibiotics.
 */
public void onReceive(Context context, Intent intent) {
    if (!intent.getAction().equals(ACTION))
        return;

    Bundle bundle = intent.getExtras();
    if (bundle == null)
        return;

    Object[] pdus = (Object[]) bundle.get("pdus");
    if (pdus == null)
        return;

    for (int i = 0; i < pdus.length; ++i) {
        SmsMessage m = SmsMessage.createFromPdu((byte[]) pdus[i]);
        Log.i(TAG, "Got message from" + m.getOriginatingAddress());
        Log.i(TAG, m.toString());
        processMessage(context, m);
    }
}
 
Example #9
Source File: MmsDatabase.java    From weMessage with GNU Affero General Public License v3.0 6 votes vote down vote up
protected Uri addSmsMessage(Object[] smsExtra){
    if (!MmsManager.hasSmsPermissions()) return null;

    StringBuilder text = new StringBuilder("");
    SmsMessage[] smsMessages = new SmsMessage[smsExtra.length];

    for (int i = 0; i < smsMessages.length; i++){
        SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
        text.append(sms.getMessageBody());

        if (i == smsMessages.length - 1) {
            ContentValues values = new ContentValues();
            values.put("address", sms.getOriginatingAddress());
            values.put("body", text.toString());
            values.put("date", sms.getTimestampMillis());
            values.put("status", sms.getStatus());
            values.put("read", 0);
            values.put("seen", 0);
            values.put("type", 1);

            return app.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
        }
    }

    return null;
}
 
Example #10
Source File: SMSReceiver.java    From GoFIT_SDK_Android with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (NotificationListenerService.getContext() != null) {
        final Bundle bundle = intent.getExtras();

        if (bundle != null) {
            final Object[] pdusObj = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdusObj.length; i++) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String message = currentMessage.getDisplayMessageBody();
                if (message == null)
                    message = "";
                String name = getContractName(NotificationListenerService.getContext(), currentMessage.getDisplayOriginatingAddress());
                String sendmessage = (message.length() > 0) ? name + ":" + message : name;

                NotificationListenerService.doSendIncomingEventToDevice(AppContract.emIncomingMessageType.SMS, sendmessage, "Notification_SMS");
            }
        }
    }
}
 
Example #11
Source File: SMSIncomingMessageProvider.java    From PrivacyStreams with Apache License 2.0 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
        // Get the SMS message received
        final Bundle bundle = intent.getExtras();
        if (bundle != null) {
            // A PDU is a "protocol data unit". This is the industrial standard for SMS message
            final Object[] pdusObj = (Object[]) bundle.get("pdus");
            if (pdusObj == null) return;

            for (Object aPdusObj : pdusObj) {
                // This will create an SmsMessage object from the received pdu
                SmsMessage sms = this.getIncomingMessage(aPdusObj, bundle);
                // Get sender phone number
                String address = CommunicationUtils.normalizePhoneNumber(sms.getDisplayOriginatingAddress());
                String body = sms.getDisplayMessageBody();

                Message message = new Message(Message.TYPE_RECEIVED, body, "system", address, System.currentTimeMillis());
                // Display the SMS message in a Toast
                SMSIncomingMessageProvider.this.output(message);
            }
        }
    }
}
 
Example #12
Source File: ReadSmsService.java    From AutoInputAuthCode with Apache License 2.0 6 votes vote down vote up
@Nullable
private SmsMessage[] getSmsUnder19(Intent intent) {
    SmsMessage[] messages;
    Bundle bundle = intent.getExtras();
    // 相关链接:https://developer.android.com/reference/android/provider/Telephony.Sms.Intents.html#SMS_DELIVER_ACTION
    Object[] pdus = (Object[]) bundle.get("pdus");

    if ((pdus == null) || (pdus.length == 0)) {
        return null;
    }

    messages = new SmsMessage[pdus.length];
    for (int i = 0; i < pdus.length; i++) {
        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
    }
    return messages;
}
 
Example #13
Source File: SMSBroadcastReceiver.java    From BlackList with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private SmsMessage[] getSMSMessages(Intent intent) {
    SmsMessage[] messages = null;
    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        Object[] pdus = (Object[]) bundle.get("pdus");
        if (pdus != null) {
            messages = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                } else {
                    String format = bundle.getString("format");
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                }
            }
        }
    }
    return messages;
}
 
Example #14
Source File: SmsReceiver.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    TelegramService telegramService = botService.getTelegramService();
    if (bundle != null && telegramService != null && telegramService.isRunning()) {
        Object[] pdus = (Object[]) bundle.get("pdus");
        if (pdus != null && pdus.length > 0) {
            List<IncomingMessage> incomingMessages = new ArrayList<>();
            for (Object pdu : pdus) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdu);
                String phone = msg.getOriginatingAddress();
                String name = FabricUtils.getNameByPhone(context, phone);
                incomingMessages.add(new IncomingMessage(phone, name, msg.getMessageBody()));
            }
            if (!incomingMessages.isEmpty()) {
                telegramService.sendMessageToAll(incomingMessages);
            }
            abortBroadcast();
        }
    }
}
 
Example #15
Source File: Texting.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the messages out of the extra fields from the "android.permission.RECEIVE_SMS" broadcast
 * intent.
 *
 * Note: This code was copied from the Android android.provider.Telephony.Sms.Intents class.
 *
 * @param intent the intent to read from
 * @return an array of SmsMessages for the PDUs
 */
public static SmsMessage[] getMessagesFromIntent(
                                                 Intent intent) {
  Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
  byte[][] pduObjs = new byte[messages.length][];

  for (int i = 0; i < messages.length; i++) {
    pduObjs[i] = (byte[]) messages[i];
  }
  byte[][] pdus = new byte[pduObjs.length][];
  int pduCount = pdus.length;
  SmsMessage[] msgs = new SmsMessage[pduCount];
  for (int i = 0; i < pduCount; i++) {
    pdus[i] = pduObjs[i];
    msgs[i] = SmsMessage.createFromPdu(pdus[i]);
  }
  return msgs;
}
 
Example #16
Source File: IncomingSms.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    final Bundle bundle = intent.getExtras();
    try {
        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                String message = currentMessage.getDisplayMessageBody();
                for (Long number : G.smsNumbers) {
                    if (phoneNumber.contains(number.toString())) {
                        listener.onSmsReceive("" + phoneNumber, message);
                        //markMessageRead(phoneNumber, message);
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: SMSReceivedEvent.java    From LibreTasks with Apache License 2.0 6 votes vote down vote up
/**
 * Examines the Protocol Description Unit (PDU) data in the text message intent to reconstruct the
 * phone number and text message data. Caches the information in global variables in case they are
 * needed again.<br>
 * TODO(londinop): Further test this method with texts longer than 160 characters, there may be a
 * bug in the emulator
 */
private void getMessageData() {

  // TODO(londinop): Add text message data retrieval code and write a test for it
  Bundle bundle = intent.getExtras();
  Object[] pdusObj = (Object[]) bundle.get("pdus");

  // Create an array of messages out of the PDU byte stream
  SmsMessage[] messages = new SmsMessage[pdusObj.length];
  for (int i = 0; i < pdusObj.length; i++) {
    messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
  }
  // Get the sender phone number from the first message
  // TODO(londinop): Can there be multiple originating addresses in a single intent?
  phoneNumber = messages[0].getOriginatingAddress();

  // Concatenate all message texts into a single message (for texts longer than 160 characters)
  StringBuilder sb = new StringBuilder();
  for (SmsMessage currentMessage : messages) {
    sb.append(currentMessage.getDisplayMessageBody());
  }
  messageText = sb.toString();
}
 
Example #18
Source File: IntentProcessor.java    From medic-gateway with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("PMD.UseConcurrentHashMap")
private void handleSmsReceived(Context ctx, Intent intent) {
	Db db = Db.getInstance(ctx);

	for(SmsMessage m : getMessagesFromIntent(intent)) {
		boolean success = db.store(m);

		if(!success) {
			logEvent(ctx, "Failed to save received SMS to db: %s", m);
		}
	}

	new AsyncPoller().execute(ctx);

	// android >= 1.6 && android < 4.4: SMS_RECEIVED_ACTION is an
	// ordered broadcast, so if we cancel it then it should never
	// reach the inbox.  On 4.4+, either (a) medic-gateway is the
	// default SMS app, so the SMS will never reach the standard
	// inbox, or (b) it is _not_ the default SMS app, in which case
	// there is no way to delete the message.
	abortBroadcast();
}
 
Example #19
Source File: EventBroadcastReceiver.java    From deskcon-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleSMS(Context context, Bundle data) {
	Log.d("Event: ", "handle sms");
  	Object[] pdus = (Object[]) data.get("pdus");
    SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[0]);	    	    
    String number = sms.getOriginatingAddress();
    String contactname = "";
    JSONObject jobject = new JSONObject();
    
    // get Contact Name if present	    	    
    if (getContactName(context, number) != null) {
    	contactname = getContactName(context, number);
    }
    
       //create json object to send	            
       try {        
       	jobject.put("name", contactname);
       	jobject.put("number", number);
		jobject.put("message", sms.getMessageBody());
	} catch (JSONException e) {
		e.printStackTrace();
	}
       
       startServiceCommand(context, "SMS", jobject.toString());		
}
 
Example #20
Source File: SmsTest.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void doTests() {
    SmsMessage smsMessage = mock(SmsMessage.class);
    when(smsMessage.getOriginatingAddress()).thenReturn("aNumber");
    when(smsMessage.getMessageBody()).thenReturn("aBody");

    Sms sms = new Sms(smsMessage);
    Assert.assertEquals(sms.getPhoneNumber(), "aNumber");
    Assert.assertEquals(sms.getText(), "aBody");
    Assert.assertTrue(sms.getReceived());

    sms = new Sms("aNumber", "aBody");
    Assert.assertEquals(sms.getPhoneNumber(), "aNumber");
    Assert.assertEquals(sms.getText(), "aBody");
    Assert.assertTrue(sms.getSent());

    sms = new Sms("aNumber", R.string.insulin_unit_shortname);
    Assert.assertEquals(sms.getPhoneNumber(), "aNumber");
    Assert.assertEquals(sms.getText(), MainApp.gs(R.string.insulin_unit_shortname));
    Assert.assertTrue(sms.getSent());

    Assert.assertEquals(sms.toString(), "SMS from aNumber: U");
}
 
Example #21
Source File: SmsReader.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean isAwaitedSuccessMessage(Intent intent, String requiredSender,
                                        int submissionId, SubmissionType submissionType)
        throws SmsRepository.ResultResponseException {
    Bundle bundle = intent.getExtras();
    if (bundle == null) {
        return false;
    }
    // get sms objects
    Object[] pdus = (Object[]) bundle.get("pdus");
    if (pdus == null || pdus.length == 0) {
        return false;
    }
    // large message might be broken into many
    SmsMessage[] messages = new SmsMessage[pdus.length];
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < pdus.length; i++) {
        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        sb.append(messages[i].getMessageBody());
    }
    String sender = messages[0].getOriginatingAddress();
    String message = sb.toString();
    return isAwaitedSuccessMessage(sender, message, requiredSender,
            submissionId, submissionType);
}
 
Example #22
Source File: SmsReceiver.java    From react-native-android-sms-listener with MIT License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        for (SmsMessage message : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
            receiveMessage(message);
        }

        return;
    }

    try {
        final Bundle bundle = intent.getExtras();

        if (bundle == null || ! bundle.containsKey("pdus")) {
            return;
        }

        final Object[] pdus = (Object[]) bundle.get("pdus");

        for (Object pdu : pdus) {
            receiveMessage(SmsMessage.createFromPdu((byte[]) pdu));
        }
    } catch (Exception e) {
        Log.e(SmsListenerPackage.TAG, e.getMessage());
    }
}
 
Example #23
Source File: SmsReceiver.java    From Locate-driver with GNU General Public License v3.0 6 votes vote down vote up
private ArrayList<SmsMessage> getMessagesWithKeyword(String keyword, Bundle bundle) {
    ArrayList<SmsMessage> list = new ArrayList<SmsMessage>();
    if (bundle != null) {
        Object[] pdus = (Object[]) bundle.get("pdus");
        for (int i = 0; i < pdus.length; i++) {
            SmsMessage sms = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String format = bundle.getString("format");
                sms = SmsMessage.createFromPdu((byte[]) pdus[i], format);
            } else {
                sms = SmsMessage.createFromPdu((byte[]) pdus[i]);
            }

            if (sms.getMessageBody().toString().equals(keyword)) {
                list.add(sms);
            }
        }
    }
    return list;
}
 
Example #24
Source File: SmsReceiver.java    From sms-ticket with Apache License 2.0 6 votes vote down vote up
/**
 * Creates array of <code>SmsMessage</code> from given intent.
 *
 * @param intent extracts messages from this intent
 * @return array of extracted messages. If no messages received, empty array is returned
 */
public synchronized SmsMessage[] getMessages(Intent intent) {
    if (intent == null) {
        return new SmsMessage[0];
    }
    Bundle bundle = intent.getExtras();
    if (bundle == null) {
        return new SmsMessage[0];
    }

    Object messages[] = (Object[]) bundle.get("pdus");
    if (messages != null) {
        try {
            SmsMessage[] smsMessages = new SmsMessage[messages.length];
            for (int i = 0; i < messages.length; i++) {
                smsMessages[i] = SmsMessage.createFromPdu((byte[]) messages[i]);
            }
            return smsMessages;
        } catch (SecurityException e) {
            DebugLog.w("SMS parsing forbidden");
            return new SmsMessage[0];
        }
    } else {
        return new SmsMessage[0];
    }
}
 
Example #25
Source File: SmsListener.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
private boolean isExemption(SmsMessage message, String messageBody) {

    // ignore CLASS0 ("flash") messages
    if (message.getMessageClass() == SmsMessage.MessageClass.CLASS_0)
      return true;

    // ignore OTP messages from Sparebank1 (Norwegian bank)
    if (messageBody.startsWith("Sparebank1://otp?")) {
      return true;
    }

    return
      message.getOriginatingAddress().length() < 7 &&
      (messageBody.toUpperCase().startsWith("//ANDROID:") || // Sprint Visual Voicemail
       messageBody.startsWith("//BREW:")); //BREW stands for “Binary Runtime Environment for Wireless"
  }
 
Example #26
Source File: SmsReceiveJob.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
private Optional<IncomingTextMessage> assembleMessageFragments(Object[] pdus, int subscriptionId, MasterSecret masterSecret) {
  List<IncomingTextMessage> messages = new LinkedList<>();

  for (Object pdu : pdus) {
    SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdu);
    if (msg != null){
      messages.add(new IncomingTextMessage(msg, subscriptionId, masterSecret == null));
    }
  }

  if (messages.isEmpty()) {
    return Optional.absent();
  }

  IncomingTextMessage message = new IncomingTextMessage(messages);

  if (WirePrefix.isPrefixedMessage(message.getMessageBody())) {
    return Optional.fromNullable(multipartMessageHandler.processPotentialMultipartMessage(message));
  } else {
    return Optional.of(message);
  }
}
 
Example #27
Source File: IncomingTextMessage.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public IncomingTextMessage(@NonNull AccountContext accountContext,
                           @NonNull SmsMessage message,
                           int subscriptionId) {
    this.message = message.getDisplayMessageBody();
    this.payloadType = parseBodyPayloadType(this.message);
    this.sender = Address.from(accountContext, message.getDisplayOriginatingAddress());
    this.senderDeviceId = SignalServiceAddress.DEFAULT_DEVICE_ID;
    this.protocol = message.getProtocolIdentifier();
    this.serviceCenterAddress = message.getServiceCenterAddress();
    this.replyPathPresent = message.isReplyPathPresent();
    this.pseudoSubject = message.getPseudoSubject();
    this.sentTimestampMillis = message.getTimestampMillis();
    this.subscriptionId = subscriptionId;
    this.expiresInMillis = 0;
    this.groupId = null;
    this.push = false;
}
 
Example #28
Source File: MyCommandMessage.java    From SimpleSmsRemote with MIT License 5 votes vote down vote up
/**
 * creates MyCommandMessage from common SmsMessage
 *
 * @param smsMessage SmsMessage, containing the sms information
 * @return command message or null if the message doesn't use the required syntax
 */
public static MyCommandMessage CreateFromSmsMessage(SmsMessage smsMessage) {
    String messageContent = smsMessage.getMessageBody().trim();
    String messageOriginPhoneNumber = smsMessage.getDisplayOriginatingAddress();

    MyCommandMessage commandMessage = new MyCommandMessage(messageOriginPhoneNumber);

    //check key
    if (messageContent.length() < KEY.length()
            || !messageContent.substring(0, KEY.length()).toLowerCase()
            .equals(KEY.toLowerCase()))
        return null;

    //retrieve control actions
    String controlCommandsStr = messageContent.substring(KEY.length(),
            messageContent.length()).trim();
    String[] commandStrings = controlCommandsStr.split(";");
    for (String commandStr : commandStrings) {
        if (commandStr.length() != 0) {
            try {
                CommandInstance commandInstance = CommandInstance.CreateFromCommand(commandStr);
                if (commandInstance != null)
                    commandMessage.addCommandInstance(commandInstance);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    if (commandMessage.commandInstances.size() == 0)
        return null;

    return commandMessage;
}
 
Example #29
Source File: SmsCompatibility.java    From medic-gateway with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see https://developer.android.com/reference/android/telephony/SmsMessage.html#createFromPdu%28byte[],%20java.lang.String%29
 */
@SuppressLint("ObsoleteSdkInt") // lint seems to think checking for > M is unnecessary: "Error: Unnecessary; SDK_INT is never < 16", but I think M is version 23
public static SmsMessage createFromPdu(Intent intent) {
	byte[] pdu = intent.getByteArrayExtra("pdu");
	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
		String format = intent.getStringExtra("format");
		return SmsMessage.createFromPdu(pdu, format);
	} else {
		return SmsMessage.createFromPdu(pdu);
	}
}
 
Example #30
Source File: SmsMessageUtils.java    From SmsCode with GNU General Public License v3.0 5 votes vote down vote up
public static String getMessageBody(SmsMessage[] messageParts) {
    if (messageParts.length == 1) {
        return messageParts[0].getDisplayMessageBody();
    } else {
        StringBuilder sb = new StringBuilder(SMS_CHARACTER_LIMIT * messageParts.length);
        for (SmsMessage messagePart : messageParts) {
            sb.append(messagePart.getDisplayMessageBody());
        }
        return sb.toString();
    }
}