android sms sending to received number - android

My goal is to create a sms server that is capable of sending sms to users who requested by sending sms... I created first broadcast receiver to receive sms and get sender num and message body..
with that body (roll no) another activity with that roll no results in marks of that person..
at first i passed message body from broadcastreceiver to activity..
Here's is my BroadcastReceiver code :
public class IncomingSms extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if(arg1.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = arg1.getExtras();
SmsMessage[] msgs = null;
String msg_from;
String msgBody;
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].getMessageBody();
Toast.makeText(arg0, "SenderNum :" + msg_from + "msg :" + msgBody, Toast.LENGTH_LONG).show();
Intent in = new Intent("SmsMessage.intent.MAIN");
in.putExtra("get_msg", msgBody);
arg0.sendBroadcast(in);
}
msg_from = msgs[0].getOriginatingAddress();
String msg = arg1.getStringExtra("string");
Toast.makeText(arg0, "Sms sent", Toast.LENGTH_LONG).show();
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(msg_from, null, msg, null, null);
} catch(Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}`
and after that message body will get compared with existing database of roll no's if found pass this string of marks to broadcastreceiver for sending SMS to user...
Here's my Activity code :
public class MyApp extends Activity implements OnClickListener
{
EditText editRollno,editName,editMarks;
Button btnAdd,btnDelete,btnModify,btnView,btnViewAll,btnShowInfo;
SQLiteDatabase db;
String s;
String s1,s2,s3;
String str,str1;
private BroadcastReceiver bd;
IncomingSms is = new IncomingSms();
String pNumber;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(is,new IntentFilter("MyReceiver"));
Intent i = new Intent("MyReceiver");
i.putExtra("string", s3);
sendBroadcast(i);
editRollno=(EditText)findViewById(R.id.editRollno);
editName=(EditText)findViewById(R.id.editName);
editMarks=(EditText)findViewById(R.id.editMarks);
btnAdd=(Button)findViewById(R.id.btnAdd);
btnDelete=(Button)findViewById(R.id.btnDelete);
btnModify=(Button)findViewById(R.id.btnModify);
btnView=(Button)findViewById(R.id.btnView);
btnViewAll=(Button)findViewById(R.id.btnViewAll);
btnShowInfo=(Button)findViewById(R.id.btnShowInfo);
btnAdd.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnModify.setOnClickListener(this);
btnView.setOnClickListener(this);
btnViewAll.setOnClickListener(this);
btnShowInfo.setOnClickListener(this);
db=openOrCreateDatabase("StudentDB", Context.MODE_WORLD_READABLE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);");
}
public void onClick(View view)
{
if(view==btnAdd)
{
if(editRollno.getText().toString().trim().length()==0||
editName.getText().toString().trim().length()==0||
editMarks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student VALUES('"+editRollno.getText()+"','"+editName.getText()+
"','"+editMarks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
if(view==btnDelete)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+editRollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==btnModify)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("UPDATE student SET name='"+editName.getText()+"',marks='"+editMarks.getText()+
"' WHERE rollno='"+editRollno.getText()+"'");
showMessage("Success", "Record Modified");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==btnView)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
editName.setText(c.getString(1));
editMarks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
if(view==btnViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
if(view==btnShowInfo)
{
showMessage("Student Management Application", "Developed By Azim");
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
editRollno.setText("");
editName.setText("");
editMarks.setText("");
editRollno.requestFocus();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter ifl = new IntentFilter("SmsMessage.intent.MAIN");
bd = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String msg = arg1.getStringExtra("get_msg");
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+ msg +"'", null);
if(c.moveToFirst())
{
s1 = c.getString(1);
s2 = c.getString(2);
s3 = s1.concat(s2);
}
else
{
}
}
};
this.registerReceiver(bd, ifl);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.unregisterReceiver(this.bd);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(is);
super.onDestroy();
}
}
After executing this,it receives the sms but not sending sms bt it toasts sms sent...i can't able to understand ..plzzz help me..Thanks in advance..

Try this:
msg_from = msgs[0].getOriginatingAddress();
String msg = arg1.getStringExtra("string");
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,new Intent(SENT), 0); // <-- add this
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(msg_from, null, msg, sentPI, null); //<-- Add this
Toast.makeText(arg0, "Sms sent", Toast.LENGTH_LONG).show(); //<-- move it here

Related

Sending SMS to multi device

This is My code to send SMS for multi devices. But the SMS is sent to only first number four times. I want to send SMS to all user stored in ArrrayList.
public class SendSMSActivity extends Activity {
Button buttonSend;
String smsBody = "Message from the API";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
textSMS = (EditText) findViewById(R.id.editTextSMS);
final ArrayList <String> phone=new ArrayList<String>();
phone.add("9742504034");
phone.add("9535179695");
phone.add("9742504034");
phone.add("7204860021");
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
for(int i = 0; i < phone.size(); i++)
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, smsBody, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
Maybe your for loop should be as follows:
SmsManager smsManager = SmsManager.getDefault();
for(String number: phone)
{
smsManager.sendTextMessage(number, null, smsBody, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show();
}

SMS activity won't send

I coding an application which when a button is pressed and a timer reaches zero, an SMS and email sends to saved contacts and the message contain information saved in preferences. I have the email sending fine and SMS seems to be working with no crashes but i don't receive any SMS at all:
#Override
public void onFinish() {
final String[] personalInfo = db.getPersonalDetails();
final Cursor contacts = db.getContacts();
if (match == false) {
sendSms();
if (db.hasGmail()) {
Thread s = new Thread(new Runnable() {
public void run() {
String args[] = db.getGmail();
GmailSender sender = new GmailSender(args[0],args[1], getApplicationContext());
Cursor c = db.getEmailContacts();
while (c.moveToNext()) {
try {
Log.e(args[0], args[1]);
sender.sendMail(
args[0],
c.getString(c
.getColumnIndex("emailAddress")));
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
}
});
s.start();
}
Toast.makeText(getApplicationContext(), "Information sent",
5000).show();
}
}
}.start();
}
private void sendSms() {
sms = new Intent(this, SMS.class);
this.startService(sms);
}
SMS Class:
public class SMS extends Service {
String BankAccount, BankNameAddress, SortCode;
String message;
SharedPreferences prefs;
public void initilizePrefs() {
prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
BankAccount = prefs.getString("BankAccount", null);
BankNameAddress = prefs.getString("BankNameAddress", null);
SortCode = prefs.getString("SortCode", null);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onStart(Intent intent, int startid) {
super.onStart(intent, startid);
initilizePrefs();
String mes = "my account info is: " + BankNameAddress + " "
+ " account number: " + BankAccount + " Sort Code is: "
+ SortCode + " " + "Thank you so much!!";
try {
if (BankNameAddress != null && BankAccount != null
&& SortCode != null) {
sendSMS("Help!! I've completely run out of money and need you to send some via bank transfer please. "
+ mes);
}
else
Toast.makeText(getBaseContext(),
"Please ensure all sections of preferences are filled",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendSMS(String message) {
Database db = new Database(this);
Cursor cursor = db.getNumbers();
db.onStop();
if (cursor != null) {
while (cursor.moveToNext()) {
String phoneNumber = cursor.getString(cursor
.getColumnIndex("number"));
Log.e("number", phoneNumber);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
you need to have a broadcast receiver which will receive your sms . the code is as follows :
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 = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");//it must be given as it is only
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); //Create an SmsMessage from a raw PDU.
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("message", str);
context.startActivity(i);
Toast.makeText(context, "mmmm"+str, Toast.LENGTH_SHORT).show();
}
}
}
In your activity class , receive the intent :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tx=(TextView) findViewById(R.id.textView1);
Bundle bun=getIntent().getExtras();
String stuff=bun.getString("message");
tx.setText("Welcome,"+stuff);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Add permisions :

How can i update my custom listView display?

I'm working on a message application and wanna update my custom listView when new message arrive. I have tried several ways to do that but was unsuccessful ...please help with complete description cause m new to android. Here my code
public class SMSBroadcastReceiver extends BroadcastReceiver {
Messages message1;
MessageDbHelper db;
Context context=null;
SmsInboxList smsInboxList;
BroadcastReceiver br;
// ADapter adap;
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter intentFilter=new IntentFilter(ACTION);
#SuppressLint("SimpleDateFormat")
#Override
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
Bundle bundle = intent.getExtras();
message1 = new Messages();
this.context=context;
// context = context.getApplicationContext();
smsInboxList = new SmsInboxList();
// adap=new ADapter(context, R.id.listView_Conversation);
MessageDbHelper dbMessagedbHelper = new MessageDbHelper(context, null,null, 0);
db = dbMessagedbHelper;
try {
if (bundle != null) {
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 senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Long localLong = Long.valueOf(currentMessage.getTimestampMillis());
String datae = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(localLong.longValue()));
/*****************
** #here we getting data for notification
**
**/
try {
message1.body(message);
message1.number(senderNum);
message1.date(datae);
message1.type("1");
Log.i("" , "body++++++++++++++++" + message1.body);
Log.i("" , "num+++++++++++" + message1.number);
Log.i("" , "date+++++++++++" + message1.date);
Log.i("" , "typeeee++++++++++++" + message1.type);
db.insertDataInMsgTable(message1);
createNotification(context, message1);
} catch (Exception e) {
Log.i("", "except" + e);
}
Log.i("SmsReceiver", "senderNum: " + senderNum
+ "; message: " + message);
}
}
}
}
public void createNotification(Context context, Messages message1) {
Log.i("", "get body====" + message1.body + "---" + message1.number);
Intent intent = new Intent(context, SmsInboxList.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("From: " + message1.number)
.setContentText(message1.body).setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.app_icon).build();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notification.flags |= Notification.DEFAULT_LIGHTS;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(0, notification);
try
{
smsInboxList.adap.notifyDataSetChanged();
}
catch(Exception e)
{
Log.i("", "error in addd==="+e);
e.printStackTrace();
}
}
}
And main activity class is
public class SmsInboxList extends Activity {
public ListView listView;
public SmsInboxListAdapter adap ;
Contact con;
MessageDbHelper dbhelper;
ProgressBar prob;
LinearLayout rell;
public static TextView newMsg;
ImageView imgv;
ImageView imgv1;
ProgressBar pd;
Dialog dialog;
ArrayList<Messages> arrList = new ArrayList<Messages>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_sms_inbox_list);
pd = new ProgressBar(SmsInboxList.this);
pd = (ProgressBar) findViewById(R.id.progressBar_Inbox);
dbhelper = new MessageDbHelper(this, null, null, 0);
dbhelper.cleartable();
Log.i("", "qwertyu==" + dbhelper.getAllreceive().size());
listView = (ListView) findViewById(R.id.listView_Conversation);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// TextView number=(TextView)findViewById(R.id.textViewName);
String addr = arrList.get(position).number; // number.getText().toString();
Log.i("" + position, "intent no==" + addr);
Intent intent = new Intent(getApplicationContext(),ConversationChat.class);
try {
String key_num = "numbrr";
intent.putExtra(key_num, addr);
Log.i("", "in intent put===" + addr);
} catch (Exception e) {
Log.i("", "putExtra==" + e);
}
startActivity(intent);
}
});
// prob=(ProgressBar)findViewById(R.id.progressBarInbox);
rell = (LinearLayout) findViewById(R.id.relativeLayout_sent);
imgv = (ImageView) findViewById(R.id.imageView_Setting);
imgv1 = (ImageView) findViewById(R.id.imageView_Compose);
newMsg = (TextView) findViewById(R.id.textView_Compose_new_message);
imgv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SendMessage.class);
startActivity(intent);
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SendMessage.class);
startActivity(intent);
}
});
// ////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////////
imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent = new Intent(getApplicationContext(),FilterAct.class);
// startActivity(intent);
dialog=new Dialog(SmsInboxList.this);
dialog.setContentView(R.layout.activity_chat_theme);
dialog.setTitle("List");
ListView
listView=(ListView)dialog.findViewById(R.id.listView_chatTheme);
ArrayList<Messagesss> arr=new ArrayList<Messagesss>();
ArrayList<Messagesss> arr_sent=new ArrayList<Messagesss>();
final int
image_rec[]={R.drawable.recieve,R.drawable.receive_rec,R.drawable.rec_recei};
final int
image_sent[]={R.drawable.sentbubble,R.drawable.sent_rec,R.drawable.rec_sent};
for(int j=0;j<image_sent.length;j++)
{
Messagesss msg1=new Messagesss();
msg1.resid=image_sent[j];
arr_sent.add(msg1);
}
for(int i=0;i<image_rec.length;i++)
{
Messagesss msg=new Messagesss();
msg.resid=image_rec[i];
arr.add(msg);
}
final CategoryListAdapter1 adapter=new
CategoryListAdapter1(SmsInboxList.this,
R.id.listView_chatTheme,arr);
try{
listView.setAdapter(adapter);
}
catch(Exception e){
Log.i("", "error in adapter call"+e);
}
dialog.show();
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
int val=adapter.getItem(position).resid;
Log.i("", ""+val);
Log.i("",
"adapter value======"+adapter.getItem(position).resid);
SharedPreferences mPrefs;
SharedPreferences.Editor editor;
mPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = mPrefs.edit();
editor.putInt("hell_receive", image_rec[position]);
editor.putInt("hell_sent", image_sent[position]);
editor.commit();
dialog.dismiss();
}
});
}
});
// /////////////////////////////////////////////////////
// //////////////////////////////////////////////
// try {
// new ProgressTas().execute("");
// } catch (Exception e) {
// Log.i("", "error Progress Task==" + e);
// }
try{
getSMSInbox();
}
catch(Exception e)
{
Log.i("","getSMSInboxttry"+e);
}
ArrayList<Messages> mymsg = new ArrayList<Messages>(
dbhelper.getAllreceive());
dbhelper.insertDataInMsgTablePrimaryKey(mymsg);
dbhelper.getAllreceiveCommon();
for (int i = 0; i < mymsg.size(); i++) {
Log.i("" + i, "my dataaaa mymsg=====" + mymsg.get(i).number + "---"
+ mymsg.get(i).body + "---" + mymsg.get(i).type);
}
try{
addItem(listView);
}
catch(Exception e)
{
Log.i("", "error in call of addItem in smsInbox"+e);
}
/*
* Log.i("", "size my msg =="+mymsg.size()); ArrayList<Messages>
* testArr=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
*
* for(int i=0;i<testArr.size();i++) { Log.i(""+i,
* "my dataaaa mymsg test====="
* +testArr.get(i).number+"---"+testArr.get(i
* ).body+"---"+testArr.get(i).type);
*
* }
*/
// setup();
// updateUi(mymsg);
}
public void chatTheme(){
}
#SuppressWarnings({ "deprecation" })
public List<String> getSMSInbox() {
List<String> sms2 = new ArrayList<String>();
Uri uri = Uri.parse("content://sms");
Cursor c = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(c);
arrList.clear();
// Read the msg data and store it in the list
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
Messages mssg = new Messages();
mssg.set_type("" + c.getString(c.getColumnIndexOrThrow("type")));
mssg.set_person(""
+ c.getString(c.getColumnIndexOrThrow("person")));
mssg.set_number(""
+ c.getString(c.getColumnIndexOrThrow("address")));
mssg.set_body("" + c.getString(c.getColumnIndexOrThrow("body")));
mssg.set_date(""
+ Functions.getTimefromMS(c.getString(c
.getColumnIndexOrThrow("date"))));
// Log.i(""+c.getString(c.getColumnIndexOrThrow("type")),
// "message==="+c.getString(c.getColumnIndexOrThrow("body")));
// Log.i(""+c.getString(c.getColumnIndexOrThrow("_id")),
// "reply path==="+c.getString(c.getColumnIndexOrThrow("reply_path_present")));
Log.i("SmsInboxList method part ",
"type===="+ c.getString(c.getColumnIndexOrThrow("type"))
+ "name===="+ c.getString(c.getColumnIndexOrThrow("person"))
+ "number=="+ c.getString(c.getColumnIndexOrThrow("address"))
+ "body===="+ c.getString(c.getColumnIndexOrThrow("body"))
+ "date===="+ c.getString(4));
dbhelper.insertDataInMsgTable(mssg);
c.moveToNext();
}
}
/*
* this is very important to dont close cursor if u dont wanna perform
* next activity and backtrack to previous activity
*/
// c.close();
// Set smsList in the arrList
adap = new SmsInboxListAdapter(getApplicationContext(), R.id.listView_Conversation);
dbhelper.insertDataInMsgTablePrimaryKey(dbhelper.getAllreceive());
arrList=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
Log.i("", "size cmn=="+arrList.size());
// listView.removeAllViews();
try {
try{
adap.notifyDataSetChanged();
}
catch(Exception e)
{
Log.i("", "error in notify dataset"+e);
}
listView.setAdapter(adap);
}
catch (Exception e) {
Log.i("", "listView" + e);
}
for (int i = 0; i < arrList.size(); i++)
{
adap.add(arrList.get(i));
Log.i("", "oyee!!!");
try{
adap.notifyDataSetChanged();
}
catch(Exception e)
{
Log.i("", "error in notify in smsInboxList=="+e);
}
}
Button button=(Button)findViewById(R.id.btn_notify);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
getSMSInbox();
Log.i("", "getSmsInbox size of array list=="+arrList.size());
}catch(Exception e)
{
Log.i("", "error in notify click");
e.printStackTrace();
}
}
});
return sms2;
//
}
}
Use
listView.invalidate();
after you have made changes to the list
Eg. you have added/removed/updated data in listView.
Just an idea:
Call your code public CategoryListAdapter1 adapter; as global to class.
Use adapter.notifyDataSetChanged(); whenever your list going to refresh.

Perfom an action on getting specific text in SMS in Android

I am trying to figure out how do I read incoming SMS messages in Android and perform a specific task, say ring an alarm, when a SMS with the text 'RingAlarm' comes in.
I figure out using the BroadcastReciever class to read the SMS, but how do I perform specific action when a message with a pre-defined text arrives. Can anyone guide me which class and/or method do I need to use for that and how?
public class IncomingSms extends BroadcastReceiver {
String key = MainActivity.keyword; //Keyword is a variable in MainActivity.
//I guess, my mistake is in accessing this variable in the IncomingSms class.
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String sms = null;
String str = "";
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
sms = msgs[i].getMessageBody().toString();
}
//---display the new SMS message---
//Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
//---compare received message with keyword
if(sms==key)
{
Toast toast = Toast.makeText(context, "Keyword Recieved", Toast.LENGTH_LONG);
toast.show();
}
}
}
Thanks in advance!
This is my simple module to solve your problem.
Let's assume that keyword is "RING".
MyReceiver : is a class file which is used to detect the keyword "RING" and going to start RingActivity.
RingActivity : is going to ring your device no matter if it is in Silent Mode or Vibrate Mode.
MyReceiver
public class MyReceiver extends BroadcastReceiver
{
final SmsManager sms = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
{
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
try
{
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
String replyPhone = msgs[0].getOriginatingAddress();
String request = msgs[0].getMessageBody().toString();
if(request.equals("RING"))
{
this.abortBroadcast();
Intent i = new Intent(context, RingActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("num", replyPhone);
i.putExtra("msg", request);
context.startActivity(i);
}
}
}
catch (Exception e)
{
Log.e("MyReceiver", "Exception smsReceiver" +e);
}
}//close if
}//close onReceive();
}
RingActivity
public class RingActivity extends Activity {
final Context context = this;
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
String num = extras.getString("num");
String msg = extras.getString("msg");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "I AM At Reciver\nsenderNum: "+num+", message: " + msg, duration);
toast.show();
SmsManager smsManager = SmsManager.getDefault();
if(IsRingerSilent() || IsVibrate())
{
smsManager.sendTextMessage(num, null, "Device turned to ringing mode.. && It's Ringing..", null, null);
AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mp.setLooping(true);
try
{
AssetFileDescriptor afd;
afd = getAssets().openFd("fire_siren.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
smsManager.sendTextMessage(num, null, "Device Ringing...", null, null);
AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mp.setLooping(true);
try
{
AssetFileDescriptor afd;
afd = getAssets().openFd("fire_siren.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// Setting Dialog Title
alertDialogBuilder.setTitle("Device Ringing");
// Setting Dialog Message
alertDialogBuilder.setMessage("Sender : "+num+"\n"+"Message : "+msg);
alertDialogBuilder.setNegativeButton("Dialog Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
if(mp.isPlaying())
{
mp.setLooping(false);
mp.stop();
}
dialog.cancel();
finish();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
//show dialog
alertDialog.show();
}
private boolean IsVibrate()
{
AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE )
{
return true;
}
else
{
return false;
}
}
private boolean IsRingerSilent()
{
AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT )
{
return true;
}
else
{
return false;
}
}
public boolean onKeyDown(int keycode, KeyEvent ke)
{
if(keycode==KeyEvent.KEYCODE_BACK)
{
if(mp.isPlaying())
{
mp.setLooping(false);
mp.stop();
}
finish();
}
return true;
}
}

How to Activate an Android App by a SMS from a specific SMS Sender (Specific SMS Port)

I need to develop an Android App which will receive SMS from a Specific sender, when the SMS received, the App has to get activated and gets all the values which came with the SMS, please provide me the answer?
You can use BroadcastReciver for reading sms. And extract that sms and save values in DataBase in android . When you call the first Activity check the particular value contains in the DataBase then only start the Activity.
public class ReadingMessage extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
DBAdapter dbHelper = new DBAdapter(context);
SmsMessage[] msgs = null;
String msg=null;
String str=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]);
msg = msgs[i].getMessageBody().toString();
str =msg.toUpperCase();
if(str.contains("your value"))
{
try{
dbHelper.open();
dbHelper.insertinfo(msg);
dbHelper.close();
}
catch(Exception e)
{
e.toString();
}
}
}
}
}
}
This code for Reading SMS.
public class StartActivity extends Activity{
private static final int ACTIVITY_REGISTRATION1=0;
private static final int ACTIVITY_SENDALERT3=1;
private static final int ACTIVITY_REGISTRATION2 = 2;
Context context;
DBAdapter dbHelper=null;
Intent intent;
String db_activation=null;
Cursor cursor;
public StartActivity()
{
this.context=this;
}
#Override
/* Method Header
* Method Name : onCreate
* Input Parameter : Bundle
* Return Value : nil
*/
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
dbHelper=new DBAdapter(this);
try
{
dbHelper.open();
cursor = dbHelper.getActivtaion();
if(cursor.getCount()==0)
{
intent=new Intent(this,Registration.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivityForResult(intent,ACTIVITY_REGISTRATION1);
}
else
{
for(int i=0;i<cursor.getCount();i++)
{
cursor.moveToNext();
db_activation = cursor.getString(cursor.getColumnIndex(DBAdapter.KEY_ACTIVATION));
if(db_activation.equals("1"))
{
intent=new Intent(this,SendAlert.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivityForResult(intent,ACTIVITY_SENDALERT3);
}
else
{
intent=new Intent(this,Registration.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivityForResult(intent,ACTIVITY_REGISTRATION2);
}
dbHelper.close();
}
}
}
catch(Exception e)
{
finish();
System.exit(0);
e.toString();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
finish();
}
}
this code for the First Activity
public long insertTruckinfo(String db_Truckmsg)
{
ContentValues cVal=new ContentValues();
cVal.put(KEY_INFO,db_Truckmsg);
return db.insert(TRUCKINFO_TABLE, null,cVal);
}
public Cursor getActivtaion()
{
Cursor cursor =db.query(ACTIVATION_TABLE, new String[] {KEY_ID,KEY_ACTIVATION}, null,null, null, null, null);
return cursor;
}
public Cursor getTruckinfo()
{
Cursor cursor =db.query(TRUCKINFO_TABLE, new String[] {KEY_ID,KEY_INFO}, null,null, null, null, null);
return cursor;
}
This is in DataBase class.
I think thi is helpful for u....
Use a broadcast receiver to capture all the incoming messages. However, where, when and how you initialize your receiver depends on your application. You can do it on boot, or on first open of your application etc.
You will have to scan all the incoming sms, read the content, and the number and check and set a flag somewhere inside your application.

Categories

Resources