Android how to get contact information from sms received? - android

I'm just done my lock screen application in Android. Now I want to improve it a bit with a notification on the lock screen when a sms received.
I got the content of the sms but I want to get the contact info of the sender. Anybody can help me to do that? Thanks in advance.

Start by getting the PDUs (Program Data Unit). From this, extract the information you desire. Search google for code examples to extract and read the data:
final Object[] pdusObj = (Object[]) bundle.get("pdus");
String who = new String();
String what = new String();
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage received = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
who = received.getDisplayOriginatingAddress();
what = received.getDisplayMessageBody();
Toast toast = Toast.makeText(contexto, "Who: " + who + "\n, What: " + what, Toast.LENGTH_LONG);
toast.show();
}

Related

Inverted Commas are not replaced by spaces and not showing in listview

I develop an SMS Application in which when a SMS is received it is saved in the listview of my application. Now the problem is that if the message contains inverted commas then it is not saving in the database and thus not showing in listview. However i tried different methods available on net but none of them work. I then use Log.e to determine whether the incoming message is replacing the inverted comma or not but it doesnot replacing the inverted comma. My code for receiving sms is:
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msg_from="";
String msgBody = "";
String msgDate="";
String title="";
if (bundle != null) {
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
msgBody += msgs[i].getDisplayMessageBody();
msgBody.replace("\"","");
Log.e("answer", msgBody);
I check in the last line but if I write "Hello and send it to my self then following error shown in logcat:
near "HELLO": syntax error (code 1):
while compiling: insert into smss(contactnumber,contactname,message,date)
values ("03329234863", "03329234863",""HELLO ","1464940881000")
I also tried to replace msgBody with these solutions but none of them work:
msgBody.replaceAll("\"","");
msgBody.replace("\"","\\\\\"");
Please Help
Removing double quotes from a String works like this in Java:
String replaced = original.replaceAll("\"", "");
So your first attempt will work as expected. If it did not work for you, you likely have an issue somewhere else, ie are not passing the replaced string to the database. You did not post that code, but I guess there's an issue somewhere.
Use this
String first = second.replaceAll("\"", "");

Reading latest received sms in Android

i saw duplicates of this question. In all the questions, they specified to read all the sms from inbox.
What i want is just to read the latest received sms.
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i < msgs.length; i++) {
// Convert Object array
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// Sender's phone number
str += "SMS from " + msgs[i].getOriginatingAddress() + " : ";
// Fetch the text message
str += msgs[i].getMessageBody().toString();
str += "\n";
}
It is extracting all the messages, So which one of the below codes do i need to use to fetch latest sms, ( I removed 'for' loop in below code )
1
msgs[0] = SmsMessage.createFromPdu((byte[]) pdus[0]);
2
msgs[0] = SmsMessage.createFromPdu((byte[]) pdus[msgs.length-1]);
Question 1 : In above two codes, which one will give me latest message, fetching pdus[0] (1) or pdus[msg.length-1] ) (2)
Quetion 2 : In my code, i am going to read latest sms and search for particular key word and do corresponding action.
When i receive 2 sms at the same time (Say SMS1 & SMS2) . My keyword is present in SMS1 .
First, SMS1 receiving and after one or two second SMS2 is receiving, so what my doubt is whether my code will read SMS1 fastly and move to read SMS2 or it will skip SMS1 when SMS2 received ?
Forgive me and do a comment if i provided anything unclear, Hope you can solve my problem . Thanks in advance. :)
Your question is weird.
The code you gave first will actually fetch only one message .
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i < msgs.length; i++) {
// Convert Object array
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// Sender's phone number
str += "SMS from " + msgs[i].getOriginatingAddress() + " : ";
// Fetch the text message
str += msgs[i].getMessageBody().toString();
str += "\n";
}
Question 1 - You must use the above code . It will fetch only one message not all the messages in inbox.
Question 2 - It will not skip

Extract OTP (6 digit) from SMS - Android

I have a broadcast receiver which listens for sms. When Sms arrives I have the whole text but am concerned with only the OTP.
My challenge is how to extract the 6 digit otp. I can't use regex because sms format might change.
example " Thanks for registering your otp is 123456"
I want 123456. sms structure can change but otp will always be a 6 digit figure
Got this working with Pattern and Matcher.
if this helps anyone (in onReceive callback of broadcast receiver) :
//---This will match any 6 digit number in the message, can use "|" to lookup more possible combinations
public Pattern p = Pattern.compile("(|^)\\d{6}");
//---retrieve the SMS message received---
try{
/**Extract sms*/
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++) //Msg Read
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
msgBody = msgs[i].getMessageBody();
}
/*
* Now extract the otp*/
if(msgBody!=null)
{
Matcher m = p.matcher(msgBody);
if(m.find()) {
otp.setText(m.group(0));
}
else
{
//something went wrong
}
}
}catch(Excep...
Please refer to this PinEntryEditText , This was a very helpful resource for me.
activity_otp.xml
<com.alimuzaffar.lib.pin.PinEntryEditText
android:id="#+id/txt_pin_entry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_14dp"
android:layout_marginEnd="#dimen/_14dp"
android:cursorVisible="false"
android:digits="1234567890"
android:inputType="number"
android:layoutDirection="ltr"
android:maxLength="6"
android:textIsSelectable="false"
android:textSize="20sp" />
OtpActivity.java
public class OptActivity {
...
#BindView(R.id.txt_pin_entry) PinEntryEditText pinEntry;
...
#OnClick(R.id.submitOtp)
void submitOtp(){
if (pinEntry.length() == 0){
Toast.makeText(context, R.string.enter_otp_to_continue , Toast.LENGTH_SHORT).show();
return;
}
if (pinEntry.length() < 6){
Toast.makeText(context, R.string.must_be_6_length, Toast.LENGTH_SHORT).show();
pinEntry.setText(null);
return;
}
//Do what you want here
}
}

The "From" tag of a sms sent via tmomail.net

It appears the true "From" tag of a message sent from an email service ex. 7135192435#tmomail.net has a diffrent "From" tag then what the message details reveal once the message is recieved through SMS. I want to be able to recieve SMS message via tmomail.net but the missing link lies in what exactly the phone sees as the "From" tag.
I have successfully recieved SMS from other cell phones, and my broadcast reciever catches them. However I can not properly set the "From" filter in order to recieve these texts via tmomail.net. Thank you in advance for all nobel android wizards, who may take time from their projects to help. What follows is the code...
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
Log.d("SMS_Project", "Beginning fired!");
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String mFrom = msgs[i].getOriginatingAddress();
String mBody = msgs[i].getMessageBody().toString();
Log.d("SMS_Project", "The From tag follows this line");
if (mFrom.equals("JimJohanson#JollyRanchers.com")) {
Log.d("SMS_Project", "above is the from tag");
if (mBody.indexOf("1") == 0) {
str += "SMS from '" + mFrom + "'";
str += " :";
str += mBody;
str += "\n";
// ---display the new SMS message---
Log.d("SMS_Project", "Toast anyone?");
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
this.abortBroadcast();
}
}
}
}
Log.d("SMS_Project", "No toast yet");}
Manifest Information:
<receiver android:name=".SmsReceiver" >
<intent-filter android:priority="99999999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
These are my permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
I suspect the propblem to be the phones lack of abilty to translate the email into a legit SMS. Perhaps it is a Multimedia Message type instead? Im going to keep combing the blue nowhere until I get this going. If you have any questions about what I have so far. Please let me know. Thanks.
Im going to try and check via the mFrom string and Log.d. For anyone else encountering this Im
//inserting...
Log.d("SMS_Project", mFrom);
//right above...
(mFrom.equals("JimJohanson#JollyRanchers.com"))
hopefully this will give me an accurate and consistent "from" tag in order to accuratley trap for a result. Can't believe its taken me this long to come up with such a simple test. Tip, learning how to properly debug and utilize LogCat is a neccessity for anyone above a copy/paste pro.
Alright disregard all of my past jaw jacking... The answer to this one is to use the getEmailFrom() function.
Example :
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String mFrom = msgs[i].getOriginatingAddress();
String mBody = msgs[i].getMessageBody().toString();
String mEmail = msgs[i].getEmailFrom().toString();
*Boolean mSomething = msgs[i].isEmail();*
Log.d("SMS_Project_From", mFrom);
Log.d("SMS_Project_mBody", mBody);
*Log.d("SMS_Project_Email", mEmail);*
This includes the Logcat so that you can identify exactly where the email is from.

Create PDU for Android

I am currently writing and application, that is sending/receiving SMS messages.
For unit-testing purposes I need to create PDU programmatically. Decoding is quite easy:
Bundle bundle = intent.getExtras();
if (bundle != null) {
/* Get all messages contained in the Intent*/
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage msg = SmsMessage.createFromPdu((byte[])pdusObj[i]);
}
}
Is there any appropriate way to create PDU programamtically?
Typically PDUs are hardcoded in the code. Similar to this:
String pdu = "07914151551512f2040B916105551511f100006060605130308A04D4F29C0E";
SmsMessage sms = SmsMessage.createFromPdu(HexDump.hexStringToByteArray(pdu));
Here's a complete example on how to do this.
Now, you're gonna ask me "where can I find a PDU for testing?" You generate it. For example, you can use this online service.
I hope this helps!!

Categories

Resources