BroadcastReceiver onReceive is not fired - android

I'm trying to cope with SMS receiving funcions in Android.
I read a lot of related topics on Stackoverflow and other sites and I tried with a very simple Class that simply print on the console that a message has been received and the message, but I cannot figure out why it doesn't work.
I see that similar questions remained unanswered in the past (see Android - Broadcast Receiver not being fired)
Hope someone could find where's the problem with my code.
Code:
package com.storassa.android.smsapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Intent recieved: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
System.out.println("Message recieved: " + messages[0].getMessageBody());
}
}
}
}
}
And Manifest
<manifest package="com.storassa.android.smsapp"
android:versionCode="1"
android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="6" android:targetSdkVersion="6"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<application android:label="#string/app_name" android:permission="android.permission.RECEIVE_SMS">
<receiver android:name="com.storassa.android.smsapp.SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
</manifest>

I tried your code, and it's working fine for me.
The post you are referring to has the problem with the setPriority set to 999 and still the broadcast aren't received.
Try setting the priority to Integer.MAX_VALUE or when in xml it should be 2147483647
Some SMS apps will use this Integer.MAX_VALUE as their priority and hence "eat" all messages received.
If it doesn't help setting setPriority to Integer.MAX_VALUE or 2147483647, then try uninstalling all apps that are handling incoming SMS'es and see if the SMS'es comes through to your app.
If this help, then it's one of the applications already installed that are eating the SMS'es.
A work-around for this, would be always to install your application as the first one. By doing this, you will always be the first application receiving the SMS broadcast.
EDIT: setting the priority to Integer.MAX_VALUE or 2147483647 is a hack and should possibly not be used. The setPriority() method only states priority from -1000 - 1000. However I use it in an app myself, but I only handle specific SMS'es received from specific numbers, so I don't see a problem in it.

This is happens when you also have installed other application which has high priority then the current one apps, so increase your priority it will start working, i also got this problem many time, in one app my priority was 100 and it was not working but when i changed it to 999, then it starts working,
So try to set different and large no priority and check it again.

//In on resume and on pause of actvities register the receiver and also in manifest
protected void onPause(){
super.onPause();
unregisterReceiver(SmsReceiver );
}
protected void onResume()
{
super.onResume();
registerReceiver(SmsReceiver ,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver SmsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};

Related

Android Service to receive SMS when app is in background

I'm currently working on an app that processes incoming SMS. As I was searching for a solution I came across different ways including stand-alone BroadcastReceivers and Services which work fine. The goal is to receive the SMS even when app is in background and screen is off (phone locked).
My current problem is: I receive any SMS with a BroadcastReceiver running within a Service. This Service is started in onResume() of my MainActivity and should not be stopped.
When my App is in foreground, all SMS are recognized by the Receiver.
Even when app is in background but my phone is still on, I can receive those messages.
The strange things happen here:
App is in foreground and I turn the screen off -->SMS are recognized.
App is in background and I turn the screen off -->SMS wont be recognized.
This is my Code for Service-class:
public class SmsProcessService extends Service {
SmsReceiver smsReceiver = new SmsReceiver();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(smsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
return START_STICKY;
}
private class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String telnr = "", nachricht = "";
Bundle extras = intent.getExtras();
if (extras != null) {
Object[] pdus = (Object[]) extras.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = getIncomingMessage(pdu, extras);
telnr = smsMessage.getDisplayOriginatingAddress();
nachricht += smsMessage.getDisplayMessageBody();
}
// Here the message content is processed within MainAct
MainAct.instance().processSMS(telnr.replace("+49", "0").replace(" ", ""), nachricht);
}
}
}
private SmsMessage getIncomingMessage(Object object, Bundle bundle) {
SmsMessage smsMessage;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = bundle.getString("format");
smsMessage = SmsMessage.createFromPdu((byte[]) object, format);
} else {
smsMessage = SmsMessage.createFromPdu((byte[]) object);
}
return smsMessage;
}
}
}
Inside my MainActivity I declare an Intent:
Intent smsServiceIntent;
which is initialized in onCreate() like this:
smsServiceIntent = new Intent(MainAct.this, SmsProcessService.class);
I start the Service in Activity onResume():
MainAct.this.startService(smsServiceIntent);
My manifest-file has <service android:name=".SmsProcessService" /> to declare the Service and following permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
I really hope, you can give me some support and help to figure out the apps's behavior.
I tried the app on different phones now and I think I have found the source of the problem.
On the other phone (same OS-Version) everything works just fine. I guess that several other apps also receive the SMS-Broadcast and maybe they disrupt each other. I didn't manage to figure out exactly which apps are the worst.
I will now try to localize other applications with similar use and hope that uninstallation or changing their notification settings will help. Have you any guess how those other apps (like "Auto Ring", which I want to use furthermore) could work parallel?
EDIT:
I found the problem causing app: It's the Google-App which also has SMS-permission granted. I deactivated it and everthing works just fine
Greets Steffen
Setting broadcast priority to 2147483647 may solve the problem as mentioned here.
<receiver android:name=".SmsReceiver">
<intent-filter android:priority="2147483647" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

Why onReceive() keeps getting called?

I want my app to send a SMS when it receives a SMS, and I got it working. The problem is that once it gets 1 SMS it doesn't stop sending them.
Its like onReceive() method keeps getting called.
I would like it to send 1 SMS per 1 SMS received.
/******************************************************************************/
BroadcastReceiver class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
public class SMSListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("031130130", null, "sms text", null, null);
}
}
/*****************************************************************************/
/***************************************************************************/
MainActivity
broadcastReceiver = new SMSListener() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED") && intent.getExtras() != null){
try{
doStuffsIfStolenOnce();
}catch (Exception e){
Toast.makeText(Running.this,"Something went wrong:" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
};
IntentFilter myFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(broadcastReceiver, myFilter);
/****************************************************************************/
added intent filter and permission in manifest
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<receiver android:name=".SMSListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
It feels like the problem is something obvious, but i can't find anybody else having this problem.
Solved my problem! Turns out it was my silly mistake, I was testing the app on my phone(real device) and i didn't have a second phone to send the "request" SMS. So I used my own phone to send the initial SMS and the app, working fine, send one back, but that meant it send a SMS to itself and once it received the second SMS it proceeded to send another one... and it got itself in a nice loop.

Using android device as a remote control

I want to make an aaplication that has the feature of controlling my phone from remotely.Such as on/off GPS through text message from another phone.Getting the location from phone via text message.
Is it possible to on/off gps through text message from another phone?
Definitely yes.
You just need to add in you application a receiver for the Action android.provider.Telephony.SMS_RECEIVED and parse the message text if you recognize ac command in your phone, you execute some code.
Basically you need to do three things:
Update you manifest abd add permission for your application to receive SMS:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
Then you have to add, again in the manifest a receiver, that receive the SMS_RECEIVED Action, in a way similar to the following:
<receiver android:name=".SMSReceiver" android:enabled="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
Where android.name is the name of your Receiver class.
And finally you have to implement that class, that extends BroadCastReceiver and has at least the onReceive Method implemented.
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
}
}
For your help, below there an example onReceive code:
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[])bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for(int i = 0; i < pdus.length; i++){
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for(SmsMessage message: messages){
String messagestr = message.getMessageBody();
String sender = message.getOriginatingAddress();
Toast.makeText(context, sender + ": " + messagestr, Toast.LENGTH_SHORT).show();
}
}
That code, read the message content and show it on a Toast. You can find a full working example here: https://github.com/inuyasha82/ItalialinuxExample/tree/master/LezioniAndroid
Recieving (handling) SMS-es is possible with Android. Your software should read the SMS, then decide if it contains command and turn off the GPS like normal app would.
This link shows how http://www.apriorit.com/dev-blog/227-handle-sms-on-android

Android SMS Receiver / Handler

I just want to ask if anyone knows or have a working SMS receiver / handler code for android. Because I've been searching the net for days now and I still haven't seen an updated code, most seem to have deprecated codes on them like the one here http://mobiforge.com/developing/story/sms-messaging-android I would REALLY appreciate it if someone could teach me the new codes for receiving SMS in an application. thanks!
I've just recently implemented a working BroadcastReceiver to handle SMS messages. The key parts are the manifest and the BroadcastReceiver.
In the manifest you need the RECEIVE_SMS permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
You don't need READ_SMS. Your receiver entry should look something like this:
<receiver
android:name=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
The bit that most people seem to forget is android:exported="true" which is required because the broadcast originates from outside your application. Some postings suggest you need android:permission="android.permission.RECEIVE_SMS" or android:permission="android.permission.BROADCAST_SMS" but this isn't the case.
My BroadcastReceiver implementation looks like this:
package smsmanager;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
final SmsMessage smsMessage = extractSmsMessage(intent);
processMessage(context, smsMessage);
}
}
private SmsMessage extractSmsMessage(final Intent intent) {
final Bundle pudsBundle = intent.getExtras();
final Object[] pdus = (Object[]) pudsBundle.get("pdus");
final SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
return smsMessage;
}
private void processMessage(final Context context, final SmsMessage smsMessage) {
// Do something interesting here
}
}
And everything works just as I want it to, and I can stop burning up my SMS allowance testing ths
This Should work, and is not deprecated, if you replace android.telephony.gsm.SmsMessage with android.telephony.SmsMessage. it's just about listening for android.provider.Telephony.SMS_RECEIVE.
There is a thread here which includes code to do what you're asking for. Note that there are some corrections in the answers there.

Android SMS receiver not working [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to write a simple application that attempts to receive SMS messages and handle them. I've followed several tutorials but I'm getting nowhere, when I send a SMS to the emulator, the Intent never seems to get fired.
Here is my intent:
package com.neocodenetworks.smsfwd;
import android.content.*;
import android.os.Bundle;
import android.telephony.*;
import android.util.Log;
public class SmsReciever extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "smsfwd";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction() == SMS_RECEIVED) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
NetComm.SendMessage("me", messages[0].getOriginatingAddress(), messages[0].getMessageBody());
}
}
}
}
}
and here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.neocodenetworks.smsfwd"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name" android:debuggable="true">
<receiver android:name=".SmsReciever">
<intent-filter>
<action android:name="android.provider.telephony.SMS_RECIEVED"></action>
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="6" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>
I'd really appreciate some guidance with what's going wrong. I'm just getting into Android development but I think I have my head wrapped around (most of) it. While monitoring the emulator's logcat, the log events never come up, and debugging breakpoints are never hit, so I have a feeling it's somewhere in my intent filter.
I'm running this on Android 2.0.1.
In addition to Samuh's answer (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 think your manifest looks okay; the problem is with the line:
if (intent.getAction() == SMS_RECEIVED) {
I think it should be: intent.getAction().equals(ACTION)
Hope that helps..
The action name seems to require a capital "T" in "Telephony.
android.provider.Telephony.SMS_RECEIVED
For String variables you should not compare with == symbol, you should compare with equals() method
this is wrong
intent.getAction() == SMS_RECEIVED)
this is right
intent.getAction().equals (SMS_RECEIVED))

Categories

Resources