Cayza Angka Maulana Cayza Angka Maulana - 1 year ago 59
Java Question

Android: Pass value from activity to broadcastreceiver

First of all, sorry for my bad grammar. I am developing Auto Reply Message Application using broadcastreceiver i have problem with when I can receive value from activity to broadcastreceiver, the Auto Reply won't work. But if I'm not receive value from Activity, it's working. this is my activity code, I put it in onSensorChanged()

Intent i = new Intent("my.action.string");
i.putExtra("apaan", lala);

and this is my broadcastreceiver class

public class AutoReply extends BroadcastReceiver{

private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("message", "Broadcast Received: " +action);

if (action.equals(SMS_RECEIVED) && action.equals("my.action.string")) {
Bundle bundle = intent.getExtras();
String state = bundle.getString("apaan");

if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] sms = new SmsMessage[pdus.length];
String isiSMS = "", noPengirim = "";
for (int i = 0; i < pdus.length; i++) {
sms[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
isiSMS = sms[i].getMessageBody();//mengambil isi pesan dari pengirim
noPengirim = sms[i].getOriginatingAddress();//mengambil no pengirim

String message = state;//isi balasan autoreplay

SmsManager smsSend = SmsManager.getDefault();
smsSend.sendTextMessage(noPengirim, null, message, null, null);

and this is my manifest

<receiver android:name=".AutoReply" android:enabled="true">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="my.action.string" />

Answer Source

The action will never be both android.provider.Telephony.SMS_RECEIVED and my.action.string.

Change this:

if (action.equals(SMS_RECEIVED) && action.equals("my.action.string")) {

To this:

if (action.equals(SMS_RECEIVED) || action.equals("my.action.string")) {

In addition, you're not sending pdus in the manually created Intent, so when you call bundle.get("pdus") it will return null. Then when you call pdus.length it will throw a NullPointerException.