Issue
I'm new to android development and java programming. i just wanted to know how to print or display certain text if this "certain" message is received. href="https://web.archive.org/web/20130327004652/http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87" rel="nofollow noreferrer">I got this code on the web on how to receive and read SMS.
ReadIncomingSms.java
package readnewsms.adk;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
}
// end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
then i added this code after toast.show(); still inside the loop
if (message.equals(("1"))){
System.out.println("user sends 1");
} else {
System.out.println("other");
}
what do i do to display those messages on the screen? or how do i evaluate the code if the message contains a certain value, then i will print a certain message depending on the message sent. for example if the INCOMING message contains 1, then the app will display user sends 1.
Solution
It looks like you want to put a Toast
on the screen. This displays a little message at the bottom. The code would look like this:
if (message.equals(("1"))){
Toast toast = Toast.makeText(context, "User sent 1");
toast.show();
} else {
Toast toast = Toast.makeText(context, "Other);
toast.show();
}
Answered By - hichris123
Answer Checked By - David Marino (JavaFixing Volunteer)