Show dialog after sms receive - android

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();

Related

How to send my location as reply when I receive a message through Broadcast Receiver?

I need to send my current Latitude and Longitude as reply to a message received through broadcast receiver.
So far i have completed the broadcast receiver and a plain text reply.Now I need to add my location to it.
Please help me with this.
This is my BroadcastReceiver class
public class SmsBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "SmsBroadcastReceiver";
private Listener listener;
public SmsBroadcastReceiver() {
}
#SuppressLint("MissingPermission")
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
String smsSender = "";
String smsBody = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.getDisplayOriginatingAddress();
smsBody += smsMessage.getMessageBody();
}
} else {
Bundle smsBundle = intent.getExtras();
if (smsBundle != null) {
Object[] pdus = (Object[]) smsBundle.get("pdus");
if (pdus == null) {
// Display some error to the user
Log.e(TAG, "SmsBundle had no pdus key");
return;
}
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
smsBody += messages[i].getMessageBody();
}
smsSender = messages[0].getOriginatingAddress();
}
}
if (smsBody.startsWith("Lost")) {
if (listener != null) {
listener.onTextReceived(smsBody);
Log.e(TAG, "SMS RECEIVED");
}
Toast.makeText(context, smsBody, Toast.LENGTH_SHORT).show();
SmsManager.getDefault().sendTextMessage(smsSender, null, "Your Phone is at latitude,longitude ", null, null);
}
}
}
void setListener(Listener listener) {
this.listener = listener;
}
interface Listener {
void onTextReceived(String text);
}
}
I have tried implementing LocationListener as an inner class but I got null value for the latitude and longitude
This happen because you don not have Permission .
get these permissions
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.BROADCAST_SMS"
tools:ignore="ProtectedPermissions" />
and for api>21
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.BROADCAST_SMS,Manifest.permission.READ_SMS},
1);

cannot read OTP from message

i m trying to read OTP from message, but i cant auto read it.please tell me what i did wrong, here is my code.i m using marshmallow. thank you.
here is my SmsReceiver class:
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for(int i=0;i<pdus.length;i++){
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
//You must check here if the sender is your provider and not another one with same text.
String messageBody = smsMessage.getMessageBody();
//Pass on the text to our listener.
mListener.messageReceived(messageBody);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}}
here is interface
public interface SmsListener {
public void messageReceived(String messageText);
}
and this is my activity
public class MyOTP extends BaseActivity implements View.OnClickListener {
EditText txtotp;
Button btnSubmitOtp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_otp);
txtotp = (EditText) findViewById(R.id.txtOtp);
btnSubmitOtp = (Button) findViewById(R.id.btnSubmit);
btnSubmitOtp.setOnClickListener(this);
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(MyOTP.this,"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
}
}
Here is my working Broadcast receiver class which will read digits from message body & broadcast with OTP code to related class
You need to add these permissions in menifest file
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission-sdk-23 android:name="android.permission.READ_SMS" />
<uses-permission-sdk-23 android:name="android.permission.RECEIVE_SMS" />
Here is my receiver class
public class SmsListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
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++) {
if (Build.VERSION.SDK_INT <= 22) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
} else {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], bundle.getString("format"));
}
msg_from = msgs[i].getOriginatingAddress();
if (msg_from.contains("PINSMS")) {
String msgBody = msgs[i].getMessageBody();
//String pinNo = msgBody.substring(msgBody.indexOf('"') + 1, msgBody.indexOf('"', msgBody.indexOf('"') + 2));
String pinNo = msgBody.replaceAll("[^0-9]", "");
Log.d("SMS", "From -" + msg_from + " : Body- " + msgBody);
//CodeVerification.insertCode(pinNo);
// Broadcast to Auto read Code sms
final String DISPLAY_MESSAGE_ACTION = context.getPackageName() + ".CodeSmsReceived";
Intent intentCodeSms = new Intent(DISPLAY_MESSAGE_ACTION);
intentCodeSms.putExtra("varificationCode", pinNo);
context.sendBroadcast(intentCodeSms);
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
I have registered this receiver in my class programmatic because i know OTP sms will come after my submit button click & i unregister it after OTP read as i dont want to trigger this receiver for every SMS by registering it in menifest.
SmsListener smsListener = new SmsListener();
try {
unregisterReceiver(smsListener);
} catch (Exception e) {
}
registerReceiver(smsListener, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
EDIT
Put below receiver in your activity to get OTP code
final String DISPLAY_MESSAGE_ACTION = activity.getPackageName() + ".CodeSmsReceived";
try {
activity.unregisterReceiver(mHandleMessageReceiver);
} catch (Exception e) {
}
activity.registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
On receiving code below method will be called
/**
* Receiving Call Log Changed broadcast
*/
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.hasExtra("varificationCode")) {
String youtOTPcode = intent.getStringExtra("varificationCode"));
}
}
};
For Marshmallow you have to ask users to give permissions. It's not given by default even if you declare it in manifest. You need to add code to get runtime permission for marshmallow devices.
For now just for checking you can go to settings --> Apps --> go to your in the list --> click on permissions --> Enable SMS permission. Then restart your app and check is it working.
Hope it will help you.
Change MyOtpActivity to
public class MyOTP extends BaseActivity{
EditText txtotp;
Button btnSubmitOtp;
private UpdateOTPReceiver mUpdateOtpReceiver;
private SMSReceiver mSmsReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_otp);
txtotp = (EditText) findViewById(R.id.txtOtp);
btnSubmitOtp = (Button) findViewById(R.id.btnSubmit);
btnSubmitOtp.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
mUpdateOtpReceiver = new UpdateOTPReceiver();
registerReceiver(mUpdateOtpReceiver, new IntentFilter("UPDATE_OTP"));
registerSMSReceiver();
}
private void registerSMSReceiver() {
mSmsReceiver = new SMSReceiver();
registerReceiver(mSmsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
private class UpdateOTPReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String msg = intent.getStringExtra("msg");
Toast.makeText(MyOTP.this,"Message: "+msg,Toast.LENGTH_LONG).show();
}
}
}
}
}
In SmsReceiver
Public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
//ToDo check your sender
String messageBody = smsMessage.getDisplayMessageBody();
Intent updateTokenIntent = new Intent("UPDATE_OTP");
updateTokenIntent.putExtra("msg", getVerificationCode(messageBody));
context.sendBroadcast(updateTokenIntent);
}
}
private String getVerificationCode(String message) {
if (message == null) {
return null;
}
int index = message.indexOf("is");
int index_last_length = message.indexOf(".");
if (index != -1) {
int start = index + 3;
return message.substring(start, index_last_length);
}
return null;
}
}
You Cannot Read a SMS having OTP word in it through broadcast receiver because of google policy.
You Cannot Read a SMS having OTP word in it through broadcast receiver because of google policy is well said by Ridhika....
OTP messages can only be read by app that has its HashCode in the message body.

How can I keep track of sent and received messages in an android messaging app?

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" />

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 :

Want to delete the messages of a specific number from the INBOX of android

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);
}
}

Categories

Resources