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.
Related
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);
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" />
The following code works well, but I think it is too complex.
SmsBroadcastReceiver.java
public class SmsBroadcastReceiver extends BroadcastReceiver{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public SmsBroadcastReceiver(){
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
PublicPar.myContext=context;
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
MSms myMSms=new MSms();
Intent msgIntent = new Intent(context,SmsInternetServer.class);
HandleSMS.SetIntentOrGetFromIntent(msgIntent, myMSms, true);
context.startService(msgIntent);
}
}
}
}
SmsInternetServer.java
public class SmsInternetServer extends IntentService {
public SmsInternetServer() {
super("SmsInternetServer");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
HandleSMS.HandleReceivedSMS(intent);
}
}
so I merge the two class in two java file into one, is it OK? and is there more simple way to simplify code? such as anonymous class.
SmsBroadcastReceiver.java
public class SmsBroadcastReceiver extends BroadcastReceiver{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public SmsBroadcastReceiver(){
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
PublicPar.myContext=context;
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
MSms myMSms=new MSms();
Intent msgIntent = new Intent(context,SmsInternetServer.class);
HandleSMS.SetIntentOrGetFromIntent(msgIntent, myMSms, true);
context.startService(msgIntent);
}
}
}
//inner class
class SmsInternetServer extends IntentService {
public SmsInternetServer() {
super("SmsInternetServer");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
HandleSMS.HandleReceivedSMS(intent);
}
}
}
You can define as many class as you want in one java file .only restriction is you can have a single public class per file.
In your case also you could have defined SMSInternet server outside the SmsBroadcastReceiver . There is no need to define it as inner class
i am developing one application that is receiving sms from inbox ,i am receiving sms successfully but my requirement is receive only new(recent)message ,i do not want to read all messages from inbox ,please help me
my Code is
public class MainActivity extends Activity {
TextView showText;
StringBuilder sb = new StringBuilder();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText = (TextView)findViewById(R.id.text);
String message = getMessagess();
showText.setText(message);
}
public String getMessagess(){
Cursor cursor=null;
Uri smsuri = Uri.parse("content://sms/inbox");
try{
cursor =getContentResolver().query(smsuri, null, null, null, null);
if (cursor == null) {
// Log.i(TAG, "cursor is null. uri: " + mSmsQueryUri);
}
for(boolean
hashdata=cursor.moveToFirst();hashdata;hashdata=cursor.moveToNext()){
final String body =
cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
final String senderNo=
cursor.getString(cursor.getColumnIndexOrThrow("address")).toString();
final String date =
cursor.getString(cursor.getColumnIndexOrThrow("date"));
final String type =
cursor.getString(cursor.getColumnIndexOrThrow("type"));
if(senderNo.equals("+XXXXXXXXXX")){
for(String bd:body.split(";"))
sb.append(bd);
sb.append("\n");
}
}
if(sb==null){
sb.append("no message found");
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
cursor.close();
}
return sb.toString();
}
}
For that you need to create BroadcastReceiver which receive SMS_RECEIVED broadcast and send alert to your application that New SMS has been arrieved.
Try with following code.
ReceiveSMSActivity :
public class ReceiveSMSActivity extends Activity {
public static TextView messageBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
messageBox=(TextView)findViewById(R.id.messageBox);
}
public static void updateMessageBox(String msg) {
messageBox.append(msg);
}
}
TextMessageReceiver :
public class TextMessageReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms) {
ReceiveSMSActivity.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
"Message: "+msg.getMessageBody()+"\n");
}
}
}
add this in your AndroidManifest.xml
<receiver android:name=".TextMessageReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
and this permission too
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Another SampleCode : How-to-receive-SMS
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();