Sergey
Sergey

Reputation: 11918

How to use PendingIntent in order to launch an application when SMS is received?

I need to launch an application when an SMS is received only from the certain number and on the certain port. If the application is already run I need to parse this message. How can I do that using PendingIntent?

Upvotes: 0

Views: 1426

Answers (1)

Sunny
Sunny

Reputation: 14818

First make the broadcastreceiver class which receive a message like this. and fire the intent of your class when sms is received.

   class SMSReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    if (bundle != null) {
      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]);
        str += "SMS from " + msgs[i].getOriginatingAddress();
        str += " :";
        str += msgs[i].getMessageBody().toString();
        str += "\n";
      }
      Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
      Intent mainActivityIntent = new Intent(context, SMS.class);
      mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(mainActivityIntent);
      Intent broadcastIntent = new Intent();
      broadcastIntent.setAction("SMS_RECEIVED_ACTION");
      broadcastIntent.putExtra("sms", str);
      context.sendBroadcast(broadcastIntent);
    }
  }
}

store the sms_sender in a string as

  String msg_sender=msg[0].getOriginatingAddress();

and give the condition after receiving message that

   if(msg_sender=(String)"your_unique_number")
   and fire the intent of your class if this condition is true.

Upvotes: 1

Related Questions