Tuesday, April 28, 2015

Android SMS receive programmatically


Sending and receiving SMS messages are fundamental features on mobile devices. Android provides API for both send and receive sms to your android application.
Here is an example for catch when your android device receive SMS to it. You need to register a broadcast receiver initially for this.

For further references use following links.
SmsManager
SmsIntents

package com.test.test.;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSValidationReceiver extends BroadcastReceiver {

    public static boolean smsRecevied = false;
    
    public SMSValidationReceiver() {
        Log.i("SMSReceiver", "SMSReceiverSMSReceiver");
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        Object[] pdus=(Object[])intent.getExtras().get("pdus");
            SmsMessage shortMessage=SmsMessage.createFromPdu((byte[]) pdus[0]);

            Log.d("SMSReceiver","SMS messge text " + shortMessage.getDisplayMessageBody());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}




In android manifest define following permission

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

Also add following to your manifest file. This will use to register your receiver.

<receiver 
     android:name=".test.SMSValidationReceiver"
     android:enabled="true" > 
 <intent-filter> 
     <action android:name="android.provider.Telephony.SMS_RECEIVED" />
 </intent-filter> 
</receiver>


No comments:

Post a Comment