Good day everyone.
I would like to make an application which replies to received SMS automatically.
For example.
Jon Doe sends me - "Hi", Application gets the message body, checks it with my database where I have a potential response:
ID | Text | Potential Answer
01 | Hi | Hello how are you?
and Application sends the Potential response.
So far what I have achieved -
App receives the Message, checks it with the database ( using Like '%') and gets the correct "Potential Answer" Column and passes it as message text body, but to send it I am using a button.
My Reciever is a sperate file class
public class MyReceiver extends BroadcastReceiver {
public static String textSmsbody="";
private static final String TAG=MyReceiver.class.getSimpleName();
public static final String pdu_type="pdus";
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceive(Context context, Intent intent) {
// Get the SMS message.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
String strMessage = "";
String format = bundle.getString("format");
// Retrieve the SMS message received.
Object[] pdus = (Object[]) bundle.get(pdu_type);
if (pdus != null) {
// Check the Android version.
boolean isVersionM =
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
// Fill the msgs array.
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
// Check Android version and use appropriate createFromPdu.
if (isVersionM) {
// If Android version M or newer:
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
} else {
// If Android version L or older:
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
// Build the message to show.
String a=msgs[i].getMessageBody();
textSmsbody=msgs[i].getMessageBody();
if (a.contains("?")) {
strMessage=msgs[i].getOriginatingAddress();
// strMessage += " :" + msgs[i].getMessageBody() + "\n";
}
else {
strMessage=a;
// strMessage += "SMS from" + msgs[i].getOriginatingAddress();
// strMessage += "ELSE:" + msgs[i].getMessageBody() + "\n";
}
// Log and display the SMS message.
Log.d(TAG, "onReceive: " + strMessage);
Toast.makeText(context, strMessage, Toast.LENGTH_LONG).show();
}
}
}
}
Sending method is in my MainActivity.
public void smsSendMessage(View view) {
databaseSearch();
// Set the destination phone number to the string in editText.
String destinationAddress = "2020";
// Find the sms_message view.
// Get the text of the SMS message.
String smsMessage = sendingText;
// Set the service center address if needed, otherwise null.
String scAddress = null;
// Set pending intents to broadcast
// when message sent and when delivered, or set to null.
PendingIntent sentIntent = null, deliveryIntent = null;
// Use SmsManager.
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage
(destinationAddress, scAddress, smsMessage,
sentIntent, deliveryIntent);
}
In layout I have a button which calls smsSendMessage () ;
My question is how I can make it automatically without button.
When the phone receives a message, the app shall check it with the database and send it by itself.
Please tell me if you need to see my Manifest file, or databasehelper.
Using JobService should be a suitable option in your case.
Create a JobService class like that
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ExampleJobService extends JobService {
#Override
public boolean onStartJob(JobParameters params) {
//send a message
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
Also Declare In your Manifest
<service
android:name=".ExampleJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
Now in your Receiver, you can start it like that
ComponentName componentName = new ComponentName(context, ExampleJobService.class);
PersistableBundle bundle = new PersistableBundle();
bundle.putLong("lat", lat);
bundle.putLong("lon", lon);
JobInfo jobInfo = new JobInfo.Builder(0, componentName)
.setExtras(bundle)
.build();
For more details about JobServices https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html
Related
So i'm working on a WhatsApp like verification system where user inputs the code received via sms and code is sent back to the server..yada yada ..all that basic stuff.
My dilemma is that i have received and read the sms correctly. How do i filter the body so that that it passes the number (not phone number but verification code) to the editText automatically. I'm trying to avoid users having to enter the verification code manually. Lemme show some code below.
public void processReceive(Context context, Intent intent){
Bundle bundle = intent.getExtras();
if(bundle == null){
return;
}
Object[] objectArray = (Object[])bundle.get("pdus");
for(int i = 0; i < objectArray.length; i++){
SmsMessage smsMsg = SmsMessage.createFromPdu((byte[])objectArray[i]);
String smsBody = smsMsg.getMessageBody();
Toast.makeText(context, smsBody, Toast.LENGTH_SHORT).show();
}
}
//In the code above, my broadcastReceiver receives the sms and i can display the body in a toast. The sms goes something like this: "Your verification code: 12345".
How do i get just the code from the sms and send its value to and editText programmatically like WhatsApp does.
number = (EditText) findViewById(R.id.number);
Thank you. You input is greatly appreciated
Try this it may be help to you
public static String GENERAL_OTP_TEMPLATE = "Your verification code: (.*).";
SmsMessage[] message = new SmsMessage[objectArray.length];
for (int i = 0; i < objectArray.length; i++) {
message[i] = SmsMessage.createFromPdu((byte[]) objectArray[i]);
}
Pattern generalOtpPattern = Pattern.compile(GENERAL_OTP_TEMPLATE);
Matcher generalOtpMatcher = generalOtpPattern.matcher(message[0].getMessageBody().toString());
if (generalOtpMatcher.find()) {
String otp = generalOtpMatcher.group(1);
number.setText(otp);
}
You can just use Split function to get your last 5 numbers :
String[] splited = body.split(":");
String mylastnum= splited[1];
number.settext(mylastnum);
hope it help !
register Broad cast Receiver in android manifest using below mention code.
<!-- SMS Receiver -->
<receiver android:name=".receiver.SmsReceiver">
<intent-filter android:priority="99999">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
Create Broad Cast Receiver using below mention code.
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (Object aPdusObj : pdusObj) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
String senderAddress = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.e(TAG, "Received SMS: " + message + ", Sender: " + senderAddress);
// if the SMS is not from our gateway, ignore the message
if (!senderAddress.toLowerCase().contains(Config.SMS_ORIGIN.toLowerCase())) {
Log.e(TAG, "SMS is not for our app!");
return;
}
// verification code from sms
String verificationCode = getVerificationCode(message);
Log.e(TAG, "OTP received: " + verificationCode);
Intent hhtpIntent = new Intent(context, HttpService.class);
hhtpIntent.putExtra("otp", verificationCode);
context.startService(hhtpIntent);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
Parse Verification Code that come through SMS.
private String getVerificationCode(String message) {
String code = null;
int index = message.indexOf(Config.OTP_DELIMITER);
if (index != -1) {
int start = index + 2;
int length = 6;
code = message.substring(start, start + length);
return code;
}
return code;
}
I have problem with starting a new activity in android. I have looked through many other questions here, but I didn't find an answer. Here's the problem:
Four classes:
1. WelcomeActivity;
2. MainActivity;
3. PopUpActivity;
4. Client;
At the begining starts WelcomeActivity where you you type all needed credentials to connect to the server, after you clicked the button, string is sent to server. Server send validation string if everything is OK. If OK is received, then MainActivity is started. Users types different things in MainActivity, the presses another button, which send another string to the server. Server processes it (string) and send back a response, also a string. And here's the problem. When server send that last string to client I want to start PopUpActivity, where will be displayed this aprticualr string in TextView.
My code:
Client part (last else if):
public void run() throws Exception {
Socket client = new Socket(ip, port);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
out.println(welcomeActivity.getCredentials());
while (true) {
final String line = in.readLine();
if (line.equals("#GO#")) {
System.out.println("#GO#");
mainActivityIntent = new Intent(welcomeActivity,
MainActivity.class);
welcomeActivity.startActivity(mainActivityIntent);
} else if (line.equals("#CLOSE#")) {
client.close();
break;
} else if (line.startsWith("#RESULTS")) {
Intent i = new Intent(MainActivity.getContext(), PopUpActivity.class);
i.putExtra(line, line);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.getContext().startActivity(i);
}
}
}
WelcomeActivity:
public void onClick(View v) {
ip = ipText.getText().toString();
port = Integer.parseInt(portText.getText().toString());
login = loginText.getText().toString();
password = passwordText.getText().toString();
credentials = login + "#" + password + "#" + brand + "#" + device + "#"
+ hardware + "#" + manufacturer + "#" + product;
client = new Client(ip, port, this);
new Handler().start();
}
private class Handler extends Thread {
public void run() {
try {
client.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
PopUpActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up);
closeButton = (Button) findViewById(R.id.closeButton);
testOutcome = (TextView) findViewById(R.id.textArea);
closeButton.setOnClickListener(this);
//
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
String value = extras.getString(Intent.EXTRA_TEXT);
if (value != null) {
testOutcome.setText(value);
}
}
PopUpActivity is started, but text is not displayed.
Before that I tried to use Context in MainActivity:
final static Context context;
....
public void onCreate() {
context = getBaseContext();
// or context = getApplicationContext();
....
}
...
public static Context getContext() {
return context;
}
And from clint tried to call:
MainActivity.getContext().getTextView().setText(line);
At the begining I tied to call a AlertDialog, but it also was bad, NullPointerException
The problem is with your intent calling, so you may write
i.putExtra("line",line); in your MainActivity
and you can retrieve it by
Intent intent = getIntent(); intent.getStringExtra("line"); in your PopUp Activity.
In my Android app, I use the Mobile Backend Starter from Google. I'd like to get a notification when the CloudEntities on the server get updated, and this notification should contain some data from the updated Entity. It works when the app is running in the background, but when I close the app (by swiping it away in the multitasking view), I can't make such a notification because I haven't got access to the CloudBackendAsync in the GCMIntentService.
I already saw this question:
Mobile Backend handle continuous queries in background
But it doesn't have a solution for the problem of accessing the cloud data in the GCMIntentService.
EDIT: My current code in GCMIntentService.java
protected void onHandleIntent(Intent intent) {
//... (Check if the GCM Message is about an update of the Mobile Backend)
// dispatch message
if (GCM_TYPEID_QUERY.equals(typeId)) {
// Here, a broadcast is sent to the Main Activity of the app, which then downloads
// the new content and shows a notification in the CloudCallbackHandler. That
// only works when the Activity is running.
// So I would like to get access to the CloudBackendAsync instance from
// the app here to download data in the background and show a notification.
Intent messageIntent = new Intent(BROADCAST_ON_MESSAGE);
messageIntent.putExtras(intent);
messageIntent.putExtra("token", tokens[2]);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
}
//...
}
The Android client does not receive the message content through the push notification event from the backend (only the subId token is sent from the demo backend which is enough to notify the client that some new message has been received for the given topic and refresh it).
So as I understand, it is not possible to directly get the entity data within the client GCMIntentService.onHandleIntent() method unless we change the backend code. I have made the following changes in the backend class ProspectiveSearchServlet so that it includes as well the message content within the push notification:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Return if push notification is not enabled
if (!backendConfigManager.isPushEnabled()) {
log.info("ProspectiveSearchServlet: couldn't send push notification because it is disabled.");
return;
}
// dispatch GCM messages to each subscribers
String[] subIds = req.getParameterValues("id");
// Each subId has this format "<regId>:query:<clientSubId>"
for (String subId : subIds) {
String regId = SubscriptionUtility.extractRegId(subId);
if (isSubscriptionActive(regId)) {
Entity matchedEntity = ProspectiveSearchServiceFactory.getProspectiveSearchService().getDocument(req);
if(matchedEntity != null) {
log.info(String.format("ProspectiveSearchServlet: matchedEntity.toString: " + matchedEntity.toString()));
} else {
log.info(String.format("ProspectiveSearchServlet: matchedEntity is null."));
}
//Add the matchedEntity object.
sendPushNotification(regId, subId, matchedEntity);
} else {
SubscriptionUtility.clearSubscriptionAndDeviceEntity(Arrays.asList(regId));
}
}
}
private void sendPushNotification(String regId, String subId, Entity matchedEntity) throws IOException {
SubscriptionUtility.MobileType type = SubscriptionUtility.getMobileType(subId);
if (SubscriptionUtility.MobileType.ANDROID == type) {
sendGcmAlert(subId, regId, matchedEntity);
} else if (SubscriptionUtility.MobileType.IOS == type) {
sendIosAlert(subId, new String[] {regId}, matchedEntity);
}
}
private void sendGcmAlert(String subId, String regId, Entity matchedEntity)
throws IOException {
String gcmKey = backendConfigManager.getGcmKey();
boolean isGcmKeySet = !(gcmKey == null || gcmKey.trim().length() == 0);
// Only attempt to send GCM if GcmKey is available
if (isGcmKeySet) {
Sender sender = new Sender(gcmKey);
if(matchedEntity != null) {
Message message = new Message.Builder().addData(SubscriptionUtility.GCM_KEY_SUBID, subId)
//extra data.<key> elements can be added here
.addData("data.message", (String) matchedEntity.getProperty("message"))
.addData("data.updatedBy", (String) matchedEntity.getProperty("_updatedBy"))
.addData("data.owner", (String) matchedEntity.getProperty("_owner"))
.addData("data.kindName", (String) matchedEntity.getProperty("_kindName"))
.build();
Result r = sender.send(message, regId, GCM_SEND_RETRIES);
if (r.getMessageId() != null) {
log.info("ProspectiveSearchServlet: GCM sent: subId: " + subId);
} else {
log.warning("ProspectiveSearchServlet: GCM error for subId: " + subId +
", senderId: " + gcmKey + ", error: " + r.getErrorCodeName());
ArrayList<String> deviceIds = new ArrayList<String>();
deviceIds.add(regId);
SubscriptionUtility.clearSubscriptionAndDeviceEntity(deviceIds);
}
}
} else {
// Otherwise, just write a log entry
log.info(String.format("ProspectiveSearchServlet: GCM is not sent: GcmKey: %s ",
isGcmKeySet));
}
}
Now on the client side you can make the following changes in the GCMIntentService to display a proper push notification (with the message body and the user name):
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
Log.i(Consts.TAG, "onHandleIntent: message error");
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
Log.i(Consts.TAG, "onHandleIntent: message deleted");
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
String subId = intent.getStringExtra(GCM_KEY_SUBID);
Log.i(Consts.TAG, "onHandleIntent: subId: " + subId);
String[] tokens = subId.split(":");
String typeId = tokens[1];
// dispatch message
if (GCM_TYPEID_QUERY.equals(typeId)) {
Intent messageIntent = new Intent(BROADCAST_ON_MESSAGE);
messageIntent.putExtras(intent);
messageIntent.putExtra("token", tokens[2]);
boolean isReceived = LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
//Check if the broadcast has been handled, if not show the notification.
if (!isReceived) {
Log.i(Consts.TAG, "A message has been recieved but no broadcast was handled.");
generateNotification(this, intent, tokens[2]);
} else {
Log.i(Consts.TAG, "A message has been recieved, broadcasted and handled.");
}
}
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
public static void generateNotification(Context context, Intent intent, String message) {
//Event keys
HashMap data = new HashMap();
for (String key : intent.getExtras().keySet()) {
Log.d(Consts.TAG, "Message key: " + key + " value: " + intent.getExtras().getString(key));
String eventKey = key.startsWith("data.") ? key.substring(5) : key;
data.put(eventKey, intent.getExtras().getString(key));
}
CharSequence contentTitle = (CharSequence) data.get("updatedBy");
if (contentTitle == null) contentTitle = "New Message";
CharSequence contentText = (CharSequence) data.get("message");
if (contentText == null) contentText = "";
CharSequence userId = (CharSequence) data.get("updatedBy");
Bitmap iconBitmap = getUserIcon(context, userId.toString());
if (iconBitmap == null) iconBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
// Creates an Intent for the Activity
Intent resultIntent = new Intent(context, GuestbookActivity.class);
// The stack builder object will contain an artificial back stack for the started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(IntroductionActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder mBuilder = new Notification.Builder(context);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(R.drawable.notification_icon)
.setLargeIcon(iconBitmap)
.setTicker(contentTitle + ": " + contentText)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.build();
///Get the notification ID, /it allows to update the notification later on.
int notifyID = 1;
String contentID = (String) data.get("id");
if(contentID != null) {
notifyID = Integer.parseInt(contentID);
}
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notifyID, notification);
}
I just set up GCM in my Android App. But I have the problem that I don't know how to check if the device is already registered. I work with the new google play services library.
The register part looks like this:
#Override
protected String doInBackground(String... arg0) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context_app);
}
regid = gcm.register(SENDER_ID);
msg = "Dvice registered, registration ID=" + regid;
Log.d("111", msg);
sendRegistrationIdToBackend(regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
How can I modify this that it checks if the device is already registered?
Store the registration id in a databade table or shared preference and when app starting..check whether it is null or not
Google has provided very clear documentation with code.You should use following code:
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered =
ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
when you get registration Id, Store it in SharedPreferences, for example:
SharedPreferences shp = context.getSharedPreferences("anyNameYouLike",MODE_PRIVATE);
SharedPreferences.Editor editor=shp.edit();
editor.putString("RegID",registrationID).commit;
In the next time before you register check the "anyNameYouLike" if it contain field called RegID Like this:
private boolean isRegistered(Context context){
SharedPreferences shp = context.getSharedPreferences("anyNameYouLike",PRIVATE_MODE);
return shp.contains("RegID");
}
I am creating an app that receives SMS text messages, I have created a class that extends BroadcastReceiver to receive and display SMS messagesin a toast within the app. I have also added permissions too my manifest along with the declaration of the receiver. The problem is it still does not seem to display the message. It will only appear on the top bar as a notification. Hopefully someone will be able to see where i am going wrong. Do i have to have some code in my mainactivity in order to display the message?? or should it display in my all my activities straight from the receiver clas?? code below:
UPDATE
I ended up deleting my receiver and recreating everything, now it seems to work fine
SmsReceiver.java:
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras ==null)
return;
//toast
Toast.makeText(context, "Received", Toast.LENGTH_LONG).show();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = SMessage.getOriginatingAddress();
String body = SMessage.getMessageBody().toString();
Intent in = new Intent("SmsMessage.intent.MAIN").putExtra("get_msg", sender+":"+body);
context.sendBroadcast(in);
this.abortBroadcast();
}
}
}
The problem is it still does not seem to display the message. It will only appear on the top bar as a notification
do you know what is - Ordered Broadcast?
in case you don't know - it's a broadcast that receives synchronously (one after another) by all receivers that registered for this broadcast. you can set in the manifest receiver deceleration a priority , and each one of the receivers can control if the broadcast will pass on in the priorities chain to additional registered receivers by using the aboartBroadcast() method.
what's to this and receiving SMS? - the system sends ordered broadcast when SMS receives. if your receivers priority is lower then the "default SMS app" priority - then what usually happens is that the application that got the broadcast first will cancel the broadcast, and you'll never receives it.
to get the broadcast before the default SMS application you have to declare your receiver with high priority (providing priority = 1000 should do the trick).
without providing priority - it's automatically set to zero.
you can have a look on this example - How Can i INTERCEPT an Incoming SMS With A specific Text
also make sure you declared the permission to RECEIVE_SMS in the manifest
Try starting again and setting up your receiver like so....
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras ==null)
return;
//toast
Toast.makeText(context, "Received", Toast.LENGTH_LONG).show();
Object[] pdus = (Object[]) extras.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = SMessage.getOriginatingAddress();
String body = SMessage.getMessageBody().toString();
Intent in = new Intent("SmsMessage.intent.MAIN").putExtra("get_msg", sender+":"+body);
context.sendBroadcast(in);
this.abortBroadcast();
}
}
}
#Override
public void onReceive(Context context, Intent arg1) {
SmsMessage msgs[] = getMessagesFromIntent(arg1);
for (int i = 0; i < msgs.length; i++) {
SmsMessage mesg = msgs[i];
Toast toast = Toast.makeText(context, mesg.getDisplayMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
}
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
// retrieve the SMS message received ::
Object[] pdus = (Object[]) extras.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";
// Toast to display SMS ::
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
// Send SMS ::
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage("put your phoneNumber(emulatorPort)", null, str, null, null);
}
}
}
--
Have nice time !
Don't forget to add permissions !