Starting an Android service from system's SMS broadcast receiver - android

Can anyone please tell me if it is possible to "wake up" my Android service as soon as there's an incoming SMS event? What I meant to say is that, whenever an SMS is received, there will be a system-wide broadcast of this event. Can I intercept this broadcast to start my own background service? I know, it's not possible to run my service permanently in the background (not to mention it's a bad design practice).
Any help would be highly appreciated!
EDIT: Adding more detail to my original question. My broadcast receiver will be wrapped inside a service class. But there is a chance the Android will kill my background service in the event of memory crunch. In that case, even if there is an incoming SMS, my service won't be fired. How can I deal with this situation? This was the main intent of the question. I know it's not possible to run my service permanently in the background (or is it possible? perhaps if I have root access?)

Create Broadcast Receiver
public class BrodcastReceiverClass extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent 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();
try {
if (senderNum.equals("MD-DOCOMO")){ //SMS Provider Name
OTPActivity Sms = new OTPActivity();
Sms.recivedSms(message);
}
} catch (Exception e) {
}
}
}
} catch (Exception e) {
}
}
}
Register BrodcastReceiver in your manifest
<receiver android:name=".BrodcastReceiverClass ">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
call in you activity for e.g your activity name is OTPActivity than write thi code in your OTPActivity.
public void recivedSms(String message) {
try {
Log.d("message is receive", message);
} catch (Exception e) {
Log.e("message not receive", e.getMessage() + "");
}
}
Add permission in manifest read sms
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

Related

Android Broadcast SMS

I want open App when receive SMS.
I try to handle this problem using Manifest-declared receivers.
Here is my code
<AndroidManifest.xml>
<receiver
android:name=".service.SMSReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
#Override
public void onReceive(Context context, Intent intent) {
packageManager = context.getPackageManager();
if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())) {
Bundle bundle = intent.getExtras();
Object[] messages = (Object[]) bundle.get("pdus");
for (Object pdu : messages)
{
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
if(message == null)
{
Log.e(TAG,"message is null");
break;
}
smsSender = message.getDisplayOriginatingAddress();
if(smsSender.compareTo(number)==0)
{
receivedData = new Date(message.getTimestampMillis());
smsBody = message.getDisplayMessageBody();
Log.i(TAG, "onReceive: "+smsBody);
SendToActivity(context,smsSender,smsBody,receivedData);
}
}
}
}
private void SendToActivity(Context context, String sender, String contents, Date receivedDate) {
Log.i(TAG, "SendToActivity: TEST ");
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_SINGLE_TOP|
Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("contents",contents);
context.startActivity(intent);
Log.i(TAG, "SendToActivity: RUN >> ");
}
this code works only when app is onPause().
I want to work even app is terminated.
Is possible that terminated app open automatically when SMS received at Android 9?
No, you can't do this. There are certain limitations that Android had put on the Broadcast Receivers.
There are certain broadcasts that Apps can't listen to, and it includes the SMS broadcast too.
You can find more about here
There are some broadcasts which your app can listen to when terminated, you can find the list here

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>

How to read SMS code from your android App

We are looking to build the functionality in our app to read a security code that being sent as part of SMS and display on the textView.
Also, I am not looking to build a broadcast receiver, may be an intent service which only will start run on a particular screen and kill the service once user navigated to another screen.
It would be great if anyone can shade some light and help with some sample code.
To read incoming SMS you have to do three things.
Broadcast Receiver
Declare Broadcast Receiver in manifest
Need SMS Receive permissions
Note: If you are compiling against 6.0 Marshmallow you have get android.permission.RECEIVE_SMS at runtime. Runtime Permissions
Lets Starts Receiving incoming SMS
1) First add permissions in manifest
<uses-permission android:name="android.permission.RECEIVE_SMS" />
2) Declare Broadcast Receiver in Manifest.
What this declaration do it will inform you when ever a new SMS Receive by device.
<receiver android:name="com.example.abc.ReciveSMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
3) Add this code to your declared class in manifest
public class ReciveSMS extends BroadcastReceiver{
private SharedPreferences preferences;
#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++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
}
Original Post here.

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

Listening to incoming texts, in the background

I'm trying to make my application listen to incoming text messages, in a persistent manner. What would be the best approach for this?
Currently, I've got a working BroadcastReceiver and I'm playing around with implementing a local service for my app. Is somehow implementing the BroadcastReceiver into the service the correct way of doing this? Will the service work in a low memory condition?
Yes broadcast receiver is best way for listening to incoming texts.if an incoming sms recvied use IntentService for your work what u want to do on sms recived.u can register a reciver for incoming sms as:
manifest file
<receiver class="SMSApp">
<intent-filter>
<action android:value="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Java File
public class SMSApp extends BroadcastReceiver{
private static final String LOG_TAG = "SMSApp";
/* package */
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals(ACTION)){
Bundle bundle = intent.getExtras();
if (bundle != null){
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 strFrom = message.getDisplayOriginatingAddress();
String strMsg = message.getDisplayMessageBody();
}
}
}
}
}
and second way you can register a ContentObserver for content://sms/inbox for listening incoming sms in inbox
The broadcast receiver does not need your application to be started, hence is the correct way of listening to incoming texts.
Just make sure to register it in the Manifest

Categories

Resources