Saturday, 15 May 2021

intent.getAction() works but intent.getStringExtra() returns null. Why?

I am passing a value from activity to broadcast receiver:

My activity code:

String stringBuilder = "Hello";
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("android.provider.Telephony.SMS_RECEIVED"); 
broadcastIntent.putExtra("message",stringBuilder);

Toast.makeText(context,broadcastIntent.getStringExtra("message"),Toast.LENGTH_SHORT).show(); //shows 'Hello' in toast

sendBroadcast(broadcastIntent);

My broadcast receiver code:

public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
        String message= intent.getStringExtra("message") //returns null
        String msg= bundle.getString("message"); //returns null too
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show(); //empty toast
        Toast.makeText(context,message,Toast.LENGTH_SHORT).show(); //empty toast
    }
}

My manifest code:

        <receiver
            android:name=".Receiver"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="2147483647" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

In my broadcast receiver, the intent can fetch the action sent, but not the string value. I've tried fetching the String value both from bundle and intent, both return null. I don't understand why, there's no mismatch in the key value too. How do I fetch the stringBuilder value from my activity?



from intent.getAction() works but intent.getStringExtra() returns null. Why?

No comments:

Post a Comment