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.
Related
I am trying to build a simple app that can notify if there is a sms incoming. Just get the broadcaster to work, but what happens is that my app crashes when I get a SMS, and then next time it get a SMS nothing happens. I don't have any error message to go after or show either.
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.studerande.upg62_b">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<receiver
android:name=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
my broadcaster class which extends BroadcastReceiver. Excuse my Toasts but I just wanted to see if it was running but it isn't..
package com.example.studerande.upg62_b;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
/**
* Created by Studerande on 2017-03-18.
*/
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);
}
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
private SmsMessage extractSmsMessage(final Intent intent) {
final Bundle pudsBundle = intent.getExtras();
final Object[] pdus = (Object[]) pudsBundle.get("pdus");
String format = pudsBundle.getString("format");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0], format);
return smsMessage;
}
else {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
return smsMessage;
}
}
private void processMessage(final Context context, final SmsMessage smsMessage) {
// Do something interesting here
Toast.makeText(context, "yo", Toast.LENGTH_SHORT).show();
}
}
MainActivity. You don't need to do anything here if I understood it correctly right?
package com.example.studerande.upg62_b;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I realized that the problem is because of the API version. The broadcaster works in phone that has API 22 or below, but not in the later versions because of the new permission-handling that was introduced. So I need to ask permission before I can read SMS. https://developer.android.com/training/permissions/requesting.html
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>
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.
I want to receive notification when the messages arrives with using Broadcast Receiver. I wrote this code but it doesnt work;
I added this code in my AndroidManifest class;
<receiver android:name=".receiver.SMSReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
And my SMSReceiver class;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
Toast.makeText(context, "New SMS: " + messages.getMessageBody(),
Toast.LENGTH_LONG).show();
Log.d(getClass().getName().toString(), "SMS Arrived");
}
}
This code must show me a Toast Message when SMS arrived. How can i fix this problem?
Thank you.
You must have the permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
If you want to send sms you will need permission :
<uses-permission android:name="android.permission.SEND_SMS" />
I think you need to register your broadcast receiver. Hope for help.
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
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) {
}
};