Why my automatic reply doesn't send sms? - android

It says null to my message, and i want to take message that i write from another class, is it possible ? Can anyone help to see what's my error ? I've tried moving button to this class too, but it wont work either,
public class ReceiveMessage extends BroadcastReceiver {
private Button btnchange;
EditText qwer;
private Context ctx;
EditText text;
TextView asd;
static TextView messageBox;
static String phoneNumber;
private EditText pesan;
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] messages = (Object[]) bundle.get("pdus");
SmsMessage[] sms = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++)
{
sms[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
break;
}
for (SmsMessage msg : sms)
{
String msga = msg.getMessageBody();
String phoneNumber1 = msg.getOriginatingAddress();
String name = getContactName(context, phoneNumber1);
if (name != null && !name.equals("null"))
{
SmsManager smsManager = SmsManager.getDefault();
String sendTo = phoneNumber1;
// i want to locate my message that i write from another class
asd = (TextView) findViewById (R.id.textView1);
qwer = (EditText) findViewById (R.id.editText1);
try {
// here's the message that i want to send but the program says null inside my msg
String smsMessage = "Hi " +name+ "\n\n" +qwer.getText().toString()+ "\n\nThx";
smsManager.sendTextMessage(sendTo, null, smsMessage, null,
null);
}catch(Exception ex){
ex.printStackTrace();
System.out.println("errror karena " +ex.getMessage());
}
}
}
}
private EditText findViewById (int e) {
return null;
}
}

You can not access the another class inflated view from this class.
You need to check if you've declare this receiver in the manifest.
Have a look on this stack overflow question.
Android - SMS Broadcast receiver

Related

SMS app received messages multiple times

I have built an SMS messaging app, which both sends and receives text messages. In MainActivity, I have a two-dimensional array of people's names and phone numbers, and in my sending class, I have a for loop which sends the same message to all of the recipients by going through each of the numbers:
for (i=0; i<names.length; i++) {
phoneNo = names[i][2] + names[i][3];
sendMessage(phoneNo, message);
}
private void sendMessage(String phoneNo, String message) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
When I send a message through the app, I can see very clearly from my own Samsung messaging app that the same message gets sent to each of the numbers in the list, which is perfect.
This is my shortened receiver class:
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSender += smgs[i].getOriginatingAddress();
infoSMS += smgs[i].getMessageBody().toString();
}
}
I have found that despite the message being sent out once to each recipient, some recipients (with this app) receive it more than once consecutively. Hence, I suspected that there was something wrong with my receiver code, which is seemingly treating one received message as several consecutive received messages. This is not a consistent problem, as different people receive the consecutive messages at different times.
However, what I've also found is that if I hardcode phoneNo in the sending class to just one phone number, or if I have only one phone number in the array in MainActivity, then this problem doesn't occur. The message still gets sent out once to that one phone number only, but the receiver will always receive it just once as intended.
I am so confused by this now, so can somebody please give some suggestions as to what I could try? Literally in the last minute, I thought that it could be a problem with createFromPdu being deprecated? If so, please advise how to change my receiver code, as I couldn't find anything which resembles my current code too much.
Many thanks in advance:-)
Do like this you are making mistake check below code.
if (bundle != null) {
// get sms objects
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// 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());
}
senderNum = messages[0].getOriginatingAddress();
message = sb.toString();
}
Update: To check default app
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
final String myPackageName = context.getPackageName();
if (Telephony.Sms.getDefaultSmsPackage(context).equals(
myPackageName)) {
// you are default
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSender += smgs[i].getOriginatingAddress();
infoSMS += smgs[i].getMessageBody().toString();
}
}
} else {
// you are not ignore
}
} else {
// for below KitKat do like normal
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSender += smgs[i].getOriginatingAddress();
infoSMS += smgs[i].getMessageBody().toString();
}
}
}
}
}
i hope this modication of your code base will help solve your problem
public class Receiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SmsMessage[] smgs = null;
String infoSender = "";
String infoSMS = "";
if (extras != null) {
try{
// Retrieve the sms message received
Object[] pdus = (Object[]) extras.get("pdus");
if(pdus.length==0){return;}
smgs = new SmsMessage[pdus.length];
for (int i = 0; i < smgs.length; i++) {
smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
infoSMS += smgs[i].getMessageBody();
}
infoSender = smgs[0].getOriginatingAddress();
}catch(Exception e){
e.printStackTrace ();
}
}
}
}

How to receive SMS in Android foreground Activity and in background?

I am receiving SMS.I want ListView to be updated as soon as SMS is received or when Activity is in the foreground.I have done this successfully as I have registered and unregistered receiver in OnResume and OnPause respectively as shown in the Code.:
BroadcastReceiver IncomingSMS = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
display_name = Util.getContactName(context, number);
DBmanager = new DbManager(context);
cursor = DBmanager.Return_All_Contacts();
String [] contactArr = showcontactsInfo(cursor);
Toast.makeText(context, contactArr[0]+"", 3000).show();
if(contactArr.length==0)
{}
else{
for(int i= 0;i<=contactArr.length;i++)
{
abortBroadcast();
}
blockMessage(context);
}
}
}
}
catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(IncomingSMS);
}
#Override
protected void onResume() {
//registerReceiver(IncomingSMS, null);
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(IncomingSMS, filter);
updateList();
}
I have also registered Receiver in the Manifest file to receive SMS when Activity is in the background.If Activity is in the background and I switch to that Activity then ListView is updated normally but if Activity is in the foreground then ListView has updated data twice. Its most probably that when Activity is in foreground two Receivers are triggered i.e the one in the foreground and second that in the manifest. How can I handle it ???? I want foreground Activity to update to receive SMS only once.
This is how I have registered Receiver in manifest and utilized in java class :
public class IncomingSMS extends BroadcastReceiver {
Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
String msg="";
Cursor cursor;
String display_name;
String flag;
ChatActivity obj_chat;
#Override
public void onReceive(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
display_name = Util.getContactName(context, number);
DBmanager = new DbManager(context);
cursor = DBmanager.Return_All_Contacts();
String [] contactArr = showcontactsInfo(cursor);
Toast.makeText(context, contactArr[0]+"", 3000).show();
if(contactArr.length==0)
{}
else{
for(int i= 0;i<=contactArr.length;i++)
{
abortBroadcast();
}
blockMessage(context);
}
}
}
}
catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
} // end for loop
// bundle is null
private String[] showcontactsInfo(Cursor cursor) {
String[] contact = new String [cursor.getCount()];
int i= 0;
while(cursor.moveToNext()){
contact[i] = cursor.getString(1);
i++;
}
return contact;
}
private void blockMessage(Context context) {
// instantiate DbMNager object to insert sms in database
//formating receiving time:
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d HH:mm:ss a");
String formatedTime = formatter.format(timestamp);
flag = "0";
DBmanager= new DbManager(context);
DBmanager.open();
DBmanager.Insert_sms_data(formatedTime ,display_name,body,flag);
DBmanager.close();
obj_chat = new ChatActivity();
obj_chat.updateList();
msg+= "SMS from " + number + " \n";
msg += body + " \n";
msg += formatedTime + " \n";
msg += flag + " \n";
Log.i("SmsReceiver", "senderNum: "+ display_name + "; message: " + body);
Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
//Toast.makeText(context, "New message received in Discrete", Toast.LENGTH_LONG).show();
}
}

how we show smilays on receiving sms in android

I make an SMS app which simple perform sending and receiving SMS ... everything is ok but when i send smilays or emojis it display emojis code not emois i used edittext for sending sms and textview for receiving sms i also changed input type into longmessage but still have the same issue ... I want to show proper smilays when anyone send me and when i send anyone ....
my english is not good plz dont mind
for example i want to send happy smile to my friend when i pick default android emojis its show me emojis code like :) :( :P not show me the emojis
private void SendSms() {
// TODO Auto-generated method stub
mPhoneNumber = FriendData.getNumber();
mMessage=messagetosend.getText().toString();
SmsManager smManager=SmsManager.getDefault();
ArrayList<String> parts = smManager.divideMessage(mMessage);
smManager.sendMultipartTextMessage(mPhoneNumber, null, parts, null, null);
//String userInput = messagetosend.getText().toString();
try
{
ContentValues values = new ContentValues();
values.put("address", mPhoneNumber);
values.put("body", mMessage);
values.put("date", DateFormat.getDateTimeInstance().format(new Date()));
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
Calendar c = Calendar.getInstance();
SenderMessages(mMessage, c.getTimeInMillis());
messagetosend.setText("");
Toast.makeText(getApplicationContext(), " Message Sent", Toast.LENGTH_LONG).show();
// finish();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
#Override
public void onReceive(Context contx, Intent intent) {
String body = "";
String number = "";
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
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]);
body += msgs[i].getMessageBody().toString();
number +=msgs[i].getOriginatingAddress();
}
}
try
{
Toast.makeText(contx, number, Toast.LENGTH_LONG).show();
Toast.makeText(contx, body, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(contx, number, Toast.LENGTH_LONG).show();
Toast.makeText(contx, body, Toast.LENGTH_LONG).show();
}
}
public void ReciverMessages(String message , long time){
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.receiver_activity, null);
mContainerView.addView(view);
TextView texttime = (TextView) view.findViewById(R.id.time_date_receiver);
TextView textmessage = (TextView) view.findViewById(R.id.tvreceiver);
//DateFormat format = new DateFormat();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String MSGDate = df.format(time);
if(MSGDate.equalsIgnoreCase(Utils.GetCurrentDate()))
{
SimpleDateFormat df1 = new SimpleDateFormat("HH:mm");
String MSGDate1 = df1.format(time);
texttime.setText(MSGDate1);
}else
{
texttime.setText(MSGDate);
}
textmessage.setText(message);
}
I found a very useful Emoticon Keyboard. This keyboard is not using Unicode sequences but rather just local image assets. I am thinking that this type of keyboard can only be useful within this app and not with other apps or Operating Systems.
So instead I am replacing the ImageView containing an asset with a TextView containing a Unicode sequence.
After cross referencing Supported Unicode Sequences as well as the Visual Unicode Database I realized that \u1F601 was a 32 bit Unicode representation, and the 16bit representation can be set like :
EditText messageInput = (EditText) findViewById(R.id.message_input);
messageInput.getText().append("\ud83d\ude01");
Implementations of Emoji (Emoticon) View/Keyboard Layouts

Best Method to store sms data in DataBase on OnReceive Method of BroadcastReceiver and then Activities get updated

I have near about six Activities and a service class with BroadcastReceiver that run in background for receiving SMS. I receive SMS on OnReceive Method of BroadcastReceiver now I would like to store incomming sms data in database for that I have made a SMSSync Class for smsProcess which pass data to dbase now I call this smsProcess on OnReceive method this work fine but I think when more sms received at same time the I got found problem I think it was due to database. Sir please tell me what is best method to store sms data after receiving it On receive and then show in activities. Sory for my bad English or if not understand. Thanks in advance sir pl revert back answer I will wait for..I tag code for On Receive method
thanks
Om Parkash Kaushik
public SMSReceiver(Context ctx){
this.context = ctx;
sync = new SMSSync(context);
dba = new DataBaseAdapter(ctx);
}
#Override
public void onReceive(Context context,final Intent intents){
if (intents.getAction().equals(ConstantClass.SMS_RECEIVED)) {
try{
Bundle bundle = intents.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String msg=null;
String temp = null;
for (SmsMessage message : messages) {
msg = message.getMessageBody();
temp = message.getOriginatingAddress();
}
if(msg.length()>5 && msg.startsWith("<") && msg.contains(">")){
String len = msg.substring(1, 3);
int tl = temp.length();
int l = tl - no;
address = temp.substring(l,tl);
int value =Integer.valueOf(len, 16).intValue();
int index = msg.indexOf(">");
if(value == index+1){
dba.Open();
int id = dba.getCordiId(address);
Cursor cur = dba.getCoord(id);
if(cur!=null)
cur.moveToFirst();
final String Phnumber = cur.getString(cur.getColumnIndex(DataBaseAdapter.Key_MbNo));
if(Phnumber.equals(address)){
int count = dba.getDeviceCount(ConstantClass.dbName[1]);
if(count<=0){
dba.InsertCurrentCoord(id,id);
}else{
Strsql = new String("UPDATE " + ConstantClass.dbName[1] + " SET " + DataBaseAdapter.Key_ReceiverCoord + " = " +
Integer.toString(id) + " WHERE " + DataBaseAdapter.Key_ID + " = ?");
dba.UpdateQuery(Strsql, Integer.toString(1));
}
dba.Close();
sync.smsProcess(msg);
abortBroadcast();
/************Now deleting the SMS from the Inbox*********************/
removeMessage(SMSReceiver.this.context, Phnumber);
if(msg.substring(3, 4).equals("2"))
ConstantClass.isAuditrequestSend = false;
/*******after receiving the sms opening the Main Screen.*****************/
if(ConstantClass.Clear_Main_Screen==true){
Intent intent = new Intent(context,ZigbeeActivity.class);
context.startActivity(intent);
}
}else{
Toast.makeText(SMSReceiver.this.context, address, Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(SMSReceiver.this.context, "message Corrupt" + address, Toast.LENGTH_LONG).show();
}
}
}
}catch(Exception e){
dlg = new ExceptionDialog(SMSReceiver.this.context,"On Sms Receiver" + address ,e.getMessage());
dlg.show();
}
}
}
I have done the same application related to yours. But instead of saving all received sms i want to save only bank transaction related sms. I hope the following code will helps you..
ReceiveSms.java
if(smsg.contains("credit") /***********/ || msg.contains("amount"))
{
Toast.makeText(context, "message related to transcation", Toast.LENGTH_SHORT).show();
dbh.smsservice(smsg);
}
DbHandler.java
public void smsservice(String sms)
{
// TODO Auto-generated method stub
String smessg="INSERT INTO SMSDETAILS(SMSMESS) VALUES('"+sms+"') ";
sdb.execSQL(smessg);
System.out.println("values of sms inserted"+smessg);
}

abortBroadcast() from activity

using the following code i can abortBroadcast() from my broadcastreciver and bundle the sms and address to my activity, what i am trying to do is abortBroadcast() from my activity,
so my activity checks if the address is the same as one of my stored addresses and then abortBroadcast(), but i cant find a way to do this, is it in any way possible to abortBroadcast() from my activity or any way of checking details from an activity then allow the broadcastreciver to abort?
heres my code:
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
// a notification message
String messages = "";
if (extras != null) {
Object[] smsExtra = (Object[]) extras.get("pdus");
for (int i = 0; i < smsExtra.length; ++i) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
String body = sms.getMessageBody().toString();// sf
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
}
Intent data = new Intent(context, Details.class);
data.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
for (int i = 0; i < smsExtra.length; ++i) {
// get sms message
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress().toString();
// bundle
Bundle bundle1 = new Bundle();
bundle1.putString("title", body);
bundle1.putString("title2", address);
data.putExtras(bundle1);
context.startActivity(data);
abortBroadcast();
}
}
}
}
in my activity:
Bundle bundle1 = this.getIntent().getExtras();
String title = bundle1.getString("title");
String title2 = bundle1.getString("title2");
((EditText) findViewById(R.id.ettext)).setText(title);
((EditText) findViewById(R.id.etnumber)).setText(title2);
mSms =(TextView)findViewById(R.id.tvsms);
String sms = mSms.getText().toString();
if (sms.equals(title2))
abortBroadcast();????
I think this post is similar enough to your problem unless I am misunderstanding. You are trying to pass data between your broadcastReceiver and your activity, correct? This post is similar and I would agree with the first response - You should setup your broadcastReceiver as a sub-class of the activity
android communicate between activity and broadcast receiver
Hope it helps, best!

Categories

Resources