i want to design an android app which show the received sms in a android toast.
i am using android studio with android 5.0 lolipop to compile.
FOLLOWING are steps which i do to create app. ( all steps are from this site)
create a new android project
enter aplication name and location
select minimum sdk as 'android 2.0'
click on add 'no activity'
create an SMSReceiver.java file under
android->app->java->com.example......->SMSReceiver.java
with following code
package com.example.vaibhav.savemev1;
import java.lang.*;
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 SMSReceiver 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();
// 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);
}
}
}
AndroidManifest.xml code is...
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vaibhav.savemev1">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<application android:allowBackup="true" android:label="#string/app_name"
android:icon="#mipmap/ic_launcher" android:theme="#style/AppTheme">
<receiver android:name=".SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
click on 'android AVD' and 'wipe' out all data in android virtual device.
click on play button and in edit configuration window
->Activity->'do not launch Activity' radio button. click on it
and ok
chose device-> launch that device which data was wiped earlier
Still no success. Am i doing anythig wrong? The App is compiling successfully, but it does not show any toast when SMS is received.
For a good answer: could you say how do you test? Do you use simulator and simulate SMS? If that so, you will need to set Data_SMS_RECEIVED in the AndroidManifest.
<receiver android:name=".SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
<!-- extent another intent-filter -->
<intent-filter>
<action android:name="android.intent.action.DATA_SMS_RECEIVED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:host="localhost" />
<data android:host="16984" />
</intent-filter>
</receiver>
With this you can use ddms or simply telnet to send a SMS to the virtual Device. like so:
telnet localhost 16984
sms send <Hello World>
text with brackets should appear. This just works with Virtual Devices. On Device the Telephony SMS_RECEIVED should do the trick.
If it not work, you should use logcat and post information form there.
Related
I am working on my first Android app, which is a paging device. It will intercept a SMS message from a certain number with a certain content in it, display that and then allow the user to send a pre-defined reply back to that same number. I have gathered up code snippets from numerous sources (including stackoverflow of course) but I haven't yet got it working.
My file structure is as shown here
The part I am struggling with is SmsBroadcastReceiver and ReceiveAlert, which should display the content of the SMS and has a button to initiate the reply.
SmsBroadcastReceiver.java looks like this:
package com.example.alert6;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String EXTRA_MESSAGE = "com.example.alert6.MESSAGE";
#Override
public void onReceive(Context context, Intent intent) {
String smsSender = "";
String smsBody = "";
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.getOriginatingAddress();
smsBody = smsMessage.getMessageBody();
}
if (smsSender.equals("+420775367297")) {
if (smsBody.contains("Test")) {
intent.putExtra(EXTRA_MESSAGE, smsBody);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // adding this flag starts the new Activity in a new Task
context.startActivity();
}
}
}
}
ReceiveAlertActivity.java is this:
package com.example.alert6;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ReceiveAlertActivity extends AppCompatActivity {
private static final int SMS_PERMISSION_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_alert);
}
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String taskingalert = intent.getStringExtra(SmsBroadcastReceiver.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView receivedAlert = findViewById(R.id.receivedAlert);
receivedAlert.setText(taskingalert);
public boolean respond(View view) {
if (!hasReadSmsPermission()) {
requestReadAndSendSmsPermission();
return false;
}
Intent intent = new Intent(this, SendResponseActivity.class);
startActivity(intent);
return false;
}
/**
* Runtime permission shenanigans
*/
private boolean hasReadSmsPermission() {
return (ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED);
}
private void requestReadAndSendSmsPermission() {
ActivityCompat.requestPermissions(ReceiveAlertActivity.this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.SEND_SMS},
SMS_PERMISSION_CODE);
}
}
And the manifest is this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.alert6">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Alert6">
<activity
android:name=".SendResponseActivity"
android:parentActivityName=".ReceiveAlertActivity">
</activity>
<activity
android:name=".ReceiveAlertActivity"
android:parentActivityName=".MainActivity">
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SmsBroadcastReceiver"
android:enabled="true"
android:exported="true"
tools:ignore="Instantiatable">
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Android Studio is showing errors in SmsBroadcastReceiver and ReceiveAlertActivity but not giving enough information to resolve them.
In SmsBroadcastReceiver, it tells me it cannot resolve method 'startActivity()'. Something needs to go in the brackets, but what?
In ReceiveAlertActivity the problems revolve around receivedalert and taskingalert. It cannot resolve setText because taskingalert is an unknown class. Obviously it's not a class, it's a string so I'm doing something wrong, but what?
Sorting out these problems may not be the end. At the moment I can't test if the app works because the build fails due to the above. Then if I get this lot working, I have some other challenges, like waking up the screen and playing a sound the broadcast receiver is triggered, and stopping the sound when the button is pressed.
You can use an Observable object in your BroadcastReceiver to store the piece of information you want to send and implement the Observer interface in your Activity so that it will be warned of every change occuring to the Observable object.
I am trying To build my first application which will send ans SMS message.
everything looks OK:
1. SMS application opens
2. The URI is inserted
3. Text message is typed
Only the last bit of pressing the "SEND" button is not performed.
I am using the code demonstrated here on youtube:
which includes this AndroidManifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="il.ac.ruppin.reco.www.sendsmsyoutube">
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.SENR_RESPONSE_VIA_MESSAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and this MainActivity.java
package il.ac.ruppin.reco.www.sendsmsyoutube;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("smsto:+972528524520");
Intent intent = new Intent(Intent.ACTION_SENDTO,uri);
intent.putExtra("sms_body","Message from my new application");
startActivity(intent);
}
}
Thanks for your help
The correct URI format for SMS is sms: (and not smsto:)
String number = "+972528524520"
Uri uri = Uri.parse("sms:" + number);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Message from my new application");
startActivity(intent);
This starts the default activity for sending an SMS message.
You can try it with the SmsManager Class
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null)
where,
phoneNo = send To , sms = your message to be passed
Ok according to Hardik Vegad answer I used the SmsManager.
What I had to do is to allow the application to send sms.
Setting>apps>MyAp>permissions
Thanks for your help
I'm developing an application in which I send notifications through Firebase. I've followed several tutorials in which the idea is to open an activity when I press the notification. This action works correctly as long as the App is open, but if it is closed or "minimized" and press the notification it is opened from the default activity, which in my case would be the SplashScreen, I really don't explain why it doesn't work. Is there anything you can recommend?
The following would be the class we know as MyFirebaseMessagingService. As you can see when I press the notification, it takes me to NotificationActivity.class and it does... but only if the application is open.
package com.asecum.com.campussicapp;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by asecum5 on 24/08/17.
*/
public class Firebase_NotificationService extends FirebaseMessagingService {
private static final String TAG = "NOTICIAS";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
/*String from = remoteMessage.getFrom();
Log.d(TAG, "Mensaje recibido de: " + from);
if(remoteMessage.getNotification() != null) {
Log.d(TAG, "Notification: " + remoteMessage.getNotification().getBody());
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
if(remoteMessage.getData().size()>0){
Log.d(TAG, "Data: " + remoteMessage.getData());
}*/
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Data: " + remoteMessage.getData());
try {
JSONObject data = new JSONObject(remoteMessage.getData());
String jsonMessage = data.getString("extra_information");
Log.d(TAG, "onMessageReceived: \n" + "Extra information: " + jsonMessage);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
showNotification(title, message);
}
}
private void showNotification(String title, String body) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_home_black_24dp)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setVibrate(new long[]{100, 250, 100, 250, 100, 250})
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
The next is the manifest... Could be possible that i forgot some permission?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.asecum.com.campussicapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SplashScreen"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".NotificationActivity">
<intent-filter>
<action android:name="NOTIFICATIONACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".Firebase_InstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".Firebase_NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
</application>
</manifest>
This is what I added in gradle
Module's build.gradle
dependencies {
...
compile 'com.google.firebase:firebase-core:10.2.6'
compile 'com.google.firebase:firebase-messaging:10.2.6'
testCompile 'junit:junit:4.12'
}
apply plugin: `com.google.gms.google-services`
Project's build.gradle
dependencies {
...
classpath 'com.google.gms:google-services:3.1.0'
}
I think this is caused by the difference between "data" style cloud messages and "notification" style cloud messages in Firebase.
For a notification style message:
FCM automatically displays the message to end-user devices on behalf
of the client app.
Also note that the firebase console can send only the notification style of message.
Could it be that this notification style cloud message arrives and is being handled automatically by the android system and not by your app (when the app is closed or in the background)?
If that is the case, then the system will open the app's default activity (splash screen) when the user clicks the notification.
As an alternative, you can send a "data" style cloud message which will be handled by your app instead of by the system. Then when the user clicks the notification, it will execute the code defined in your .Firebase_NotificationService
From a Mac command line, you can use an a script like this to send a data style message through Google's servers to a particular app instance id:
curl -X POST \
--Header "Authorization: key=<get authorization key from Firebase console - Project Settings - Web API Key>” \
--Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send \
-d " \
{ \
\"to\”:\”<get id for your particular android device app instance from Firebase Instance ID service in your app>\”, \
\"data\": \
{ \
\"title\":\" test title here \", \
\"body\":\" test body here \"
}, \
\"priority\": \"normal\" \
}"
Notice that there is no "notification" block in the JSON.
See also this and this
I am writing an sms receiver android code but it is not working.
It compiles will but when I get an sms it did not displayed as supposed to be when using Toast.
This is my code:
package com.example.homecontrolingbysms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
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 messageReceived = "";
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]);
messageReceived +="From "+ msgs[i].getOriginatingAddress();
messageReceived+=" : ";
messageReceived += msgs[i].getMessageBody().toString();
messageReceived += "\n";
}
//---display the new SMS message---
Toast.makeText(context, messageReceived, Toast.LENGTH_SHORT).show();
}
}
}
I also posted manifest to make sure all important parts of code are available
manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.homecontrolingbysms"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.homecontrolingbysms.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.homecontrolingbysms.Door"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.homecontrolingbysms.Window"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.homecontrolingbysms.Light"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
Register smsreceiver by adding below code in menifest file
<receiver android:name="com.shreymalhotra.smsreceiver.SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
This links may help you.
Receiving SMS on Android App
http://shreymalhotra.me/blog/tutorial/receive-sms-using-android-broadcastreceiver-inside-an-activity/
Please check it.
if you want to receive some broadcasts , blew things must be done.
1. In the manifest.xml ,you must declare your receiver with the intent filter
exp:
2. if the broadcast that you want to receive is ordered, you must make sure your priority.
android:priority="1000"
I think your manifest looks okay; the problem is with the line:
Mistake is in this part I think can you change this
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String messageReceived = "";
if (bundle != null)
to something like this
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
intent.getAction().equals(ACTION) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
(you need to do an object comparison on the action string, or just do no comparison), in your manifest file you have misspelled SMS_RECEIVED.
I've been puzzling over this one recently, prior to 2.3.5 this seems to work fine (on my colleagues devices). However on mine it now never triggers.
I've stripped the code right back and made a very simple test application to see what's going on. Basically the onReceive code doesn't ever appear to trigger, even though adb/logcat does seem to show the register of the BroadcastReveiver does take place.
Here's the simple code I've gone for:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcasttech.testsmsreceive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="9" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".TestSMSReceiveActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".mysmstestcall">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>
Then:
package com.broadcasttech.testsmsreceive;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
public class TestSMSReceiveActivity extends Activity {
private BroadcastReceiver receiver;
private static final String TAG = "TestSMSApp";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, " App has started up");
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
Log.i(TAG, " Filter SMS_RECEIVED has been added");
//Extends BroadcastReceiver
receiver = new mysmstestcall();
registerReceiver(receiver,filter);
Log.i(TAG, " registerReceiver sorted");
}
//Also, to save headaches later
#Override
protected void onDestroy() {
Log.i(TAG, " unregistering Receiver");
unregisterReceiver(receiver);
Log.i(TAG, " done");
}
}
And finally
package com.broadcasttech.testsmsreceive;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class mysmstestcall extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "TestSMSApp";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction() == SMS_RECEIVED) {
//any action you want here..
Log.i(TAG, "SMS received has triggered");
}
}
}
So it is a fairly simple app that should just log and tell me when the BroadcastReceiver is triggered, but it just won't fire at all.
Can anyone suggest whats wrong, I've checked various tutorials, checked as I know IceCreamSandwich is different, but tried to incorporate those fixes too and this doesn't make a difference either.
Thanks in advance!
The main problem is that this line in "mysmstestcall" is wrong:
if (intent.getAction() == SMS_RECEIVED)
should be changed to this:
if (intent.getAction().equals(SMS_RECEIVED))
Is there a reason that you have two recievers? You have a programatic listener and you have an XML listener
Programatic:
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
Log.i(TAG, " Filter SMS_RECEIVED has been added");
//Extends BroadcastReceiver
receiver = new mysmstestcall();
XML Listener:
<receiver android:name=".mysmstestcall">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
Are you sure you want these two? If you have two you will RECEIVE the same broadcast 2 times...
As for another ISSUE that I see is this line
if (intent.getAction() == SMS_RECEIVED)
When comparing strings you DO NOT compare them like this instead you'd have something like this:
if (intent.getAction().equalsIgnoreCase(SMS_RECEIVED))
I've got this once. It can be network's issue. These were my question and answer. You can add a sending intent and catch the result code. In my case, it was RESULT_ERROR_GENERIC_FAILURE. I tried to find other solutions for months but no luck, so I accepted that even though I don't want to :-(
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsBroadcastReceiver extends BroadcastReceiver{
public static final String SMS_BUNDLE = "pdus";
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, "A new message is added to the SMS List!!!\n"+smsMessageStr, Toast.LENGTH_SHORT).show();
//this will update the UI with message
InboxMain inst = InboxMain.instance();
inst.updateList(smsMessageStr);
}
}
}
manifest::
<receiver android:name=".SmsBroadcastReceiver" android:permission="android.permission.BROADCAST_SMS" android:exported="true">
<intent-filter android:priority="2147483647" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
permission::
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />