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 :
Related
I'm new to Android development (but not to Java) and I'm writing my own Android messaging app that hopefully should take the place of the default SMS app. My question is - how does the default SMS app keep track of sent and received messages and how might I accomplish the same task? Specifically, I can't figure out how to find, store, and display a conversation history between the device user and a member of their contact list. I don't have any preliminary code yet, because frankly, I have no idea where to begin.
EDIT: Trying to set up a BroadcastReceiver as a first step (gotta start somewhere) but I'm struggling getting my app to fire when the notification comes through the device (I'm using emulators).
Here is my BroadcastReceiver Class (based on example from below)
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
public class smsBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "smsBroadcastReceiver";
private static final String SMS_SENT = "android.provider.Telephony.SMS_SENT";
final SmsManager mySMSManager = SmsManager.getDefault();
String phoneNumber, message;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) handleIncMessage(intent.getExtras(), context);
else if (intent.getAction().equals(SMS_SENT)) sendSMS(intent.getExtras(), context);
}
void sendSMS(Bundle bundle, Context context){
phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
Log.e("info", "Outgoing Number: " + phoneNumber);
context.sendBroadcast(new Intent("onNewMsgSend"));
}
void handleIncMessage(Bundle bundle, Context context) {
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
//database stuff...
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
String sendingNum = messages[i].getDisplayOriginatingAddress();
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String message = messages[i].getDisplayMessageBody();
Intent msgIntent = new Intent(context, conversationView.class);
msgIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(msgIntent);
// Log.i(TAG, "SENDER: " + sendingNum +"; Message: " + message);
System.out.println("SENDER: " + sendingNum +"; Message: " + message);
}
context.sendBroadcast(new Intent("onNewMsg"));
}
}
}
My best guess is that I'm doing something wrong in my Activities, but I'm not sure what. Do I need to send my intent to my main (launching) activity and then delegate the intent from there, or can I send it to an activity that isn't the launcher (which is what I'm trying to do now)?
EDIT: BroadcastReceiver problem solved.
Try this way,hope this will help you to solve your problem
Step 1.
This is your first home class
public class MainActivity extends Activity {
Context context;
Activity act;
ListView lvsms;
public static String msg = "msg", phoneNo = "phoneNo", time = "time";
public static String typeMsg = "0";
public static String typeSend = "1";
// String typeDeliver = "2";
TextView smsno_record;
SimpleCursorAdapter adapter1;
BroadcastReceiver onNewMsg = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
BroadcastReceiver onNewMsgSend = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
// BroadcastReceiver deliveredreceiver = new BroadcastReceiver() {
// #Override
// public void onReceive(Context context, Intent intent) {
//
// }
// };
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onNewMsg);
unregisterReceiver(onNewMsgSend);
// unregisterReceiver(deliveredreceiver);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(onNewMsg, new IntentFilter("onNewMsg"));
registerReceiver(onNewMsgSend, new IntentFilter("onNewMsgSend"));
// registerReceiver(deliveredreceiver, new IntentFilter(
// "deliveredreceiver"));
setContentView(R.layout.complete_sms_data);
context = MainActivity.this;
act = MainActivity.this;
lvsms = (ListView) findViewById(R.id.lvsms);
smsno_record = (TextView) findViewById(R.id.smsno_record);
smsdetails(typeMsg);// sendboxSMS();
}
void smsdetails(String type) {
Database db = new Database(context);
// ArrayList<HashMap<String, String>> al = db.getRecord(type);
LinkedList<HashMap<String, String>> al = db.getRecord(type);
Log.e("test", "sms al :- " + al.size());
db.close();
for (int i = 0; i < al.size(); i++) {
HashMap<String, String> hm = al.get(i);
String name = getName(getContentResolver(), hm.get(phoneNo));
hm.put("name", hm.get(phoneNo) + " " + name);
Log.e("test", "name :- " + name);
}
if (al.size() > 0) {
lvsms.setVisibility(View.VISIBLE);
CustomAdapter adapter = null;
if (type.equals(typeMsg)) {
Log.e("test", "if condition 1st");
adapter = new CustomAdapter((Activity) context, al);
lvsms.setAdapter(adapter);
// adapter = new SimpleAdapter(context, al,
// R.layout.list_items_msgs, new String[] { "name", msg,
// time }, new int[] { R.id.txtPhoneNo,
// R.id.txtMsg, R.id.txtTime });
} else if (type.equals(typeSend)) {
Log.e("test", "if condition 2st");
adapter = new CustomAdapter((Activity) context, al);
lvsms.setAdapter(adapter);
// adapter = new SimpleAdapter(context, al,
// R.layout.list_items_msgs, new String[] { "name", msg,
// time }, new int[] { R.id.txtPhoneNo,
// R.id.txtMsg, R.id.txtTime });
}
// else if (type.equals(typeDeliver)) {
// adapter = new SimpleAdapter(context, al,
// R.layout.list_items_msgs, new String[] { "name", msg,
// time }, new int[] { R.id.txtPhoneNo,
// R.id.txtMsg, R.id.txtTime });
// }
lvsms.setAdapter(adapter);
smsno_record.setVisibility(View.GONE);
} else {
Log.e("test", "else condition ");
lvsms.setAdapter(null);
lvsms.setVisibility(View.GONE);
}
}
}
Step 2.
This is your receiver for sms
public class Receiver extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
String phoneNumber, message;
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
"android.provider.Telephony.SMS_RECEIVED")) {
handleIncomingMsg(intent.getExtras(), context);
} else if (intent.getAction().equals(
"android.provider.Telephony.SMS_SENT")) {
sendSMS(intent.getExtras(), context);
}
}
void handleIncomingMsg(Bundle bundle, Context context) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
Database db = new Database(context);
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();
Intent in1 = new Intent(context, MainActivity.class);
in1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(in1);
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: "
+ message);
db.insertRecord(senderNum, message, MainActivity.typeMsg);
}
context.sendBroadcast(new Intent("onNewMsg"));
db.close();
}
void sysAlert(String title, String msg, Context context) {
AlertDialog alert = new AlertDialog.Builder(context).setTitle(title)
.setMessage(msg)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.setCanceledOnTouchOutside(false);
alert.show();
}
public void onDestroy() {
telephony.listen(null, PhoneStateListener.LISTEN_NONE);
}
TelephonyManager telephony;
MyPhoneStateListener phoneListener;
boolean ring = false;
boolean callReceived = false;
void handleCalls(Context context) {
if (phoneListener == null) {
phoneListener = new MyPhoneStateListener(context);
telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
}
void sendSMS(Bundle bundle, Context context) {
phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
Log.e("info", "Outgoing Number: " + phoneNumber);
Database db = new Database(context);
db.insertRecord(phoneNumber, "hii", MainActivity.typeSend);
//
// }
db.close();
context.sendBroadcast(new Intent("onNewMsgSend"));
}
}
Sept 3.
Put permissions in mainfest
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
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
I want to receive sms and show Dialog.
How can i do that?
SmsReceiver:
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 = "";
String num = "";
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]);
if (i==0) {
//---get the sender address/phone number---
num += msgs[i].getOriginatingAddress();
}
//---get the message body---
str += msgs[i].getMessageBody().toString();
}
//---display the new SMS message---
if (num.equals("+XXXXXXXXX")){
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
//What to do here?
}
//---prevent this SMS message from being broadcasted---
abortBroadcast();
Log.d("SMSReceiver", str);
}
}
}
My Main:
public class MainActivity extends FragmentActivity implements YesNoDialogListener {
GoogleMap googleMap;
Marker marker = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// get my actual position and display a blue dot
googleMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation();
if( myLocation != null ){
Toast.makeText(this, "Latitude: " + myLocation.getLatitude() + "\nLongitude: " + myLocation.getLongitude(), Toast.LENGTH_SHORT).show();
}
if( myLocation == null ){
Toast.makeText(this, "Chujnia", Toast.LENGTH_SHORT).show();
}
}
}
//==Dialog yes/no
public void btnShowYesNoDialog(View view) {
showYesNoDialog();
}
public void showYesNoDialog() {
FragmentManager fragmentManager = getSupportFragmentManager();
YesNoDialogFragment yesnoDialog = new YesNoDialogFragment();
yesnoDialog.setCancelable(false);
yesnoDialog.setDialogTitle("New accident");
yesnoDialog.show(fragmentManager, "yes/no dialog");
}
#Override
public void onFinishYesNoDialog(boolean state) {
Toast.makeText(this, "Returned from dialog: " + state,
Toast.LENGTH_SHORT).show();
SmsManager sms = SmsManager.getDefault();
if (state == true){
sms.sendTextMessage("+XXXXXX", null, "OK", null, null);
}
else{
sms.sendTextMessage("+XXXXXXX", null, "No", null, null);
}
}
}
How to execute btnShowYesNoDialog from SmsReceive?
Now it works only when I press the button which is connected to btnShowYesNoDialog?
If you need to receive sms during application opened (not as service), you can put Receiver in Main activity as mentioned in hewwcn answer.
For example:
public class MainActivity extends Activity {
/*
* Variables for BroadcastReceiver
*/
boolean isRegistered = false; // check if BroadcastReceiver registered
private IntentFilter filterSmsReceived = new IntentFilter(
"android.provider.Telephony.SMS_RECEIVED");
/**
* Create BroadcastReceiver
*/
private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
"android.provider.Telephony.SMS_RECEIVED")) {
/* get the SMS message passed in */
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msgFrom = null;
String msgBody = null;
if (bundle != null) {
/* retrieve the SMS message received */
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]);
msgFrom = msgs[i].getOriginatingAddress();
msgBody = msgs[i].getMessageBody();
}
/*
* TODO Show dialog
*/
} catch (Exception e) {
// Log.d("Exception caught",e.getMessage());
}
}
}
}
};
/**
* Button - register BroadcastReceiver when clicked (or put it to onCreate)
*/
public void onButtonClicked(View v) {
this.registerReceiver(smsReceiver, filterSmsReceived);
isRegistered = true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPause() {
/*
* Unregister BroadcastReceiver
*/
if (isRegistered) {
this.unregisterReceiver(smsReceiver);
isRegistered = false;
}
super.onPause();
}
#Override
protected void onDestroy() {
/*
* Unregister BroadcastReceiver
*/
if (isRegistered) {
this.unregisterReceiver(smsReceiver);
isRegistered = false;
}
super.onDestroy();
}
}
you can put SMSReceiver into MainActivity :
public class MainActivity extends FragmentActivity implements YesNoDialogListener {
private BroadcastReceiver SMSReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//TODO
}
};
}
Remember to register the broadcast receiver
update.
sorry.I didnt read your code carefully.I think you need android application.
public class MyApplication extends Application{
private static MyApplication instance;
public static MyApplication getInstance(){
return instance;
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
androidmanifest:
<application
android:name="xx.xx.MyApplication">
then you can show Toast or dialog in onReceive method:
Toast.makeText(MyApplication.getInstance(), "ok", Toast.LENGTH_LONG).show();
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;
}
}
I want to delete the messages from a specific mobile no. in android phone.
For this,I am using the following code..
The Problem in this code is that it is deleting all the conversations from the phone..
So help me please to resolve this problem.
THANX IN ADVANCE...
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// String specificPhoneNumber = "+91" ;
super.onCreate(savedInstanceState);
long V;
MainActivity thr = new MainActivity();
V =thr.getThreadId(thr);
Uri thread = Uri.parse("content://sms/inbox/8767564523" + V);
getContentResolver().delete(thread, null, null);
}
private long getThreadId(Context context)
{
long threadId = 0;
String SMS_READ_COLUMN = "read";
String WHERE_CONDITION = SMS_READ_COLUMN + " = 0";
String SORT_ORDER = "date DESC";
int count = 0;
Uri uri1 = Uri.parse("content://sms/inbox/");
Cursor cursor = context.getContentResolver().query(uri1,new String[] { "_id", "thread_id", "address", "person", "date", "body" },WHERE_CONDITION,null,SORT_ORDER);
if (cursor != null) {
try {
count = cursor.getCount();
if (count > 0) {
cursor.moveToFirst();
threadId = cursor.getLong(1);
}
} finally {
cursor.close();
}
}
return threadId;
}
}
Oh...Got it ..It is Working 100%,
public void onReceive(Context context, Intent intent) {
//Bundle bundle = intent.getExtras();
// if(null == bundle)
// return;
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
try {
// Java reflection to gain access to TelephonyManager's
// ITelephony getter
tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Log.v("1","BYE BYE BYE" );
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
// com.android.internal.telephony.ITelephony
telephonyService = (ITelephony) m.invoke(tm);
Bundle b = intent.getExtras();
incommingNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(context, incommingNumber, Toast.LENGTH_LONG).show();
Log.v("2","BYE BYE BYE" );
for(int i=0;i<1;i++)
{
if ( incommingNumber.equals(BINO[i]) )
{
}
else{
Toast.makeText(context,incommingNumber, Toast.LENGTH_LONG).show();
telephonyService = (ITelephony) m.invoke(tm);
//telephonyService.silenceRinger();
telephonyService.endCall();
Log.v("3","BYE BYE BYE" );
//telephonyService.answerRingingCall();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};//BroadcastReceiver
/**
* Broadcast receiver to detect the outgoing calls.
*/
public class OutgoingReceiver extends BroadcastReceiver
{
public OutgoingReceiver() {
}
#Override
public void onReceive(Context context, Intent intent)
{
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// setResultData(null);
int c = (number).indexOf("YOUR NO...");
Toast.makeText(context, String.valueOf(c), Toast.LENGTH_LONG).show();
for(int i =0;i<2;i++)
{
if ((number).indexOf(BONO[i])!= -1)//||number.contentEquals("+917204302689")||number.contentEquals("07204302689"))
{
setResultData(null);
Toast.makeText(context, "This call is not allowed!", Toast.LENGTH_LONG).show();
}
}
}
}
public class MessageReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
//Bundle bundle = intent.getExtras();
if ( bundle != null )
{
// do you manipulation on String then if you can abort.
}
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]);
}
for(int i=0;i<1;i++)
{
if(MINO[i].equalsIgnoreCase(smsMessage[0].getOriginatingAddress()))
{
//abortBroadcast();
String Body=smsMessage[0].getMessageBody();
if (Body.startsWith("START"))
{
Toast toast4 = Toast.makeText(context,"There is START ", Toast.LENGTH_LONG);toast4.show();
abortBroadcast();
}
}
else
{
abortBroadcast();
}
}
// show first message
Toast toast1 = Toast.makeText(context,"Received SMS: " + smsMessage[0].getOriginatingAddress()+ "\nBody: "+smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast1.show();
}
};//BroadcastReceiver
String incommingNumber;
private Context ctx;
private TelephonyManager tm;
//private CallStateListener callStateListener;
ITelephony telephonyService;
private OutgoingReceiver outgoingReceiver;
private IncomingReceiver incomingReceiver;
private MessageReceiver messageReceiver;
public CallHelper(Context ctx)
{
this.ctx = ctx;
//callStateListener = new CallStateListener();
outgoingReceiver = new OutgoingReceiver();
incomingReceiver = new IncomingReceiver();
messageReceiver = new MessageReceiver();
}
/**
* Start calls detection.
*/
public void start() {
//tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
//tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
ctx.registerReceiver(outgoingReceiver, intentFilter);
IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
ctx.registerReceiver(incomingReceiver, filter);
IntentFilter filter1= new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
ctx.registerReceiver(messageReceiver, filter1);
}
/**
* Stop calls detection.
*/
public void stop()
{
//tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
ctx.unregisterReceiver(outgoingReceiver);
ctx.unregisterReceiver(incomingReceiver);
ctx.unregisterReceiver(messageReceiver);
}
}