Vishal Afre Vishal Afre - 1 year ago 86
Android Question

Detecting incoming SMS using BroadcastReceiver not working

I'm developing an android app which will detect and scan the SMS for its content even when my application is closed. I know that BroadcastReceiver is the solution for this and I've developed the code, but unfortunately not getting the output as expected.

Here is my Activity file

public class SMSBroadcastReceiver extends BroadcastReceiver {

private static final String TAG = SMSBroadcastReceiver.class.getSimpleName();
public static final String SMS_CONTENT = "sms_content";

public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());

Cursor c = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
String smsBody = c.getString(12);
Toast.makeText(context, "SMS RECEIVED:", Toast.LENGTH_LONG).show();
Toast.makeText(context, smsBody, Toast.LENGTH_LONG).show();

I've also included these lines in my Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>

<receiver android:name=".SMSBroadcastReceiver">
<action android:name="android.provider.telephony.SMS_RECEIVED"/>

Plz help me to find out what is going wrong and I'm not able to Toast the incoming SMS...

Answer Source

First of all sorry for answering so late, but just went through it now and thought sharing my solution would also help some. Actually, the only problem was I was not starting the broadcast anywhere. I just added the lines

sendBroadcast(new Intent(MyActivity.this, SMSBroadcastReceiver.class));