Search code examples
androidbroadcastreceiversmsmanager

SMS Receiving broadcast receiver does not seem to work


I am preparing an app which requires me to have user's phone number and then send a hashcode the user programatically as SMS so that it will be used as their token afterwards.

I am making the user enter the number in the MainActivty and have my receiver which listens to SMS_RECEIVED so that it will notiy the user, first of all I want to make sure I am sending and receiving the user's number correctly and receving it. However my receiver does not seems to listen to the trigger. I can see the received sms on notification as well as I can hear the sound but broadcast receiver does not listens to it.

My Code for MainActivity is

public class MainActivity extends Activity
{    
Button submit;
EditText contact;
static String phNo;
ProgressDialog progress;
static Boolean wasMyOwnNumber;
static Boolean workDone;
final static int SMS_ROUNDTRIP_TIMOUT = 30000;

@Override
protected void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  contact = (EditText)findViewById(R.id.mobileNumber);
  submit = (Button) findViewById(R.id.button1);
  wasMyOwnNumber = false;
  workDone = false;
  submit.setOnClickListener(new View.OnClickListener()
  {
          public void onClick(View v)
          {
              phNo = contact.getText().toString();
              new CheckOwnMobileNumber().execute();
          }
  });

}

 private class CheckOwnMobileNumber extends AsyncTask<String, Void, String>
 {
  @Override
  protected void onPostExecute(String result)
  {
      // TODO Auto-generated method stub
      if(progress.isShowing())
      {
          progress.dismiss();
          if(wasMyOwnNumber)
          {
              Toast.makeText(getApplicationContext(), "Number matched.", Toast.LENGTH_LONG).show();
              wasMyOwnNumber = false;
              workDone = false;
          }
          else
          {
              Toast.makeText(getApplicationContext(), "Wrong number.", Toast.LENGTH_LONG).show();
              wasMyOwnNumber = false;
              workDone = false;
              return;
          }
      }
      super.onPostExecute(result);
  }

  @Override
  protected String doInBackground(String... params)
  {
      // TODO Auto-generated method stub
      String msg = phNo;
      try
      {
          SmsManager sms = SmsManager.getDefault();
          sms.sendTextMessage(phNo, null, msg, null, null);
          timeout();
      }
      catch(Exception ex)
      {
          Log.v("Exception :", ""+ex);
      }
      return null;
  }

  @Override
  protected void onPreExecute() 
  {
      // TODO Auto-generated method stub
      progress = ProgressDialog.show(MainActivity.this, "","Checking Mobile Number...");
      progress.setIndeterminate(true);
      progress.getWindow().setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
      super.onPreExecute();
  }

}

 private boolean timeout()
 {
     int waited = 0;
     while (waited < SMS_ROUNDTRIP_TIMOUT)
     {
        try
        {
          Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        waited += 100;
        if(phoneNumberConfirmationReceived())
        {
            waited=SMS_ROUNDTRIP_TIMOUT;
            workDone = true;
        }
     }
     /*Log.v("MainActivity:timeout2: Waited: " , ""+waited);
     Log.v("MainActivity:timeout2:Comparision: ", ""+ phoneNumberConfirmationReceived());
     Log.v("MainActivity:timeout2: WorkDone value after wait complete : ", ""+workDone);*/
  return workDone;

}

 private boolean phoneNumberConfirmationReceived()
 {
  if(wasMyOwnNumber)
  {
      workDone = true;
  }
  return workDone;

} MyCode for SMSReceiver is

public class SMSReceiver extends BroadcastReceiver
{
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
Context mContext;
private Intent mIntent;
static String address, str = null;
boolean isSame;

// Retrieve SMS
public void onReceive(Context context, Intent intent)
{
    Log.v("ONMESSAGE", "RECEIVED");
    mContext = context;
    mIntent = intent;
    String action = intent.getAction();       
        SmsMessage[] msgs = getMessagesFromIntent(mIntent);
        if (msgs != null)
        {
            for (int i = 0; i < msgs.length; i++)
            {
                address = msgs[i].getOriginatingAddress();
                str = msgs[i].getMessageBody().toString();
            }
        }
        Log.v("Originating Address : Sender :", ""+address);
        Log.v("Message from sender :", ""+str);
        isSame = PhoneNumberUtils.compare(str, MainActivity.phNo);
        Log.v("Comparison :", "Yes this true. "+isSame);
        if(isSame)
        {
             MainActivity.wasMyOwnNumber = isSame;
             MainActivity.workDone=true;
        }

        // ---send a broadcast intent to update the SMS received in the
        // activity---
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("SMS_RECEIVED_ACTION");
        broadcastIntent.putExtra("sms", str);
        context.sendBroadcast(broadcastIntent);

   }

public static SmsMessage[] getMessagesFromIntent(Intent intent)
{
    Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
    byte[][] pduObjs = new byte[messages.length][];

    for (int i = 0; i < messages.length; i++)
    {
        pduObjs[i] = (byte[]) messages[i];
    }

    byte[][] pdus = new byte[pduObjs.length][];
    int pduCount = pdus.length;
    SmsMessage[] msgs = new SmsMessage[pduCount];
    for (int i = 0; i < pduCount; i++)
    {
        pdus[i] = pduObjs[i];
        msgs[i] = SmsMessage.createFromPdu(pdus[i]);
    }
    return msgs;
}
}  

*My entries in Manifest is *

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getphonenumber"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/> 
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.getphonenumber.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>
     <receiver android:name="com.example.getphonenumber.SMSReceiver">  
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</application>

</manifest>

Solution

  • Give a priority value for the intent..

    change your <intent-filter> as following

    <intent-filter android:priority="999" >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
    

    Have a try..

    Also add permission to receive sms

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