Android : How can i use Broadcast Receiver in android?

on Friday, August 15, 2014


I want to receive notification when the messages arrives with using Broadcast Receiver. I wrote this code but it doesnt work;


I added this code in my AndroidManifest class;



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


And my SMSReceiver class;



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
Toast.makeText(context, "New SMS: " + messages.getMessageBody(),
Toast.LENGTH_LONG).show();
Log.d(getClass().getName().toString(), "SMS Arrived");
}

}


This code must show me a Toast Message when SMS arrived. How can i fix this problem? Thank you.


0 comments:

Post a Comment