First you need to add uses-permission to READ SMS.
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
Then This is the code line for receive SMS.
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.util.Log; import android.widget.Toast; public class ReceiveSms extends BroadcastReceiver { final SmsManager sms = SmsManager.getDefault(); public void onReceive(Context context, Intent intent) { final Bundle bundle = intent.getExtras(); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdusObj.length; i++) { SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); String phoneNumber = currentMessage.getDisplayOriginatingAddress(); String senderNum = phoneNumber; String message = currentMessage.getDisplayMessageBody(); int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration); toast.show(); } } } catch (Exception e) { Log.e("SmsReceiver", "Exception smsReceiver" + e); } } }
And Finally you have to Add your receiver in manifest file(Inside application tags).You must be add android:priority="500" other wise it will not work.
<receiver android:name="com.example.HomeControlSystem.ReceiveSms"> <intent-filter android:priority="500"> <action android:name="android.provider.Telephony.SMS_RECEIVED" /></intent-filter> </receiver>
Happy coding..
No comments:
Post a Comment