2

How to send a data from a broadcast receiver to fragment? Here I want to send the phonenumber (OriginatingAddress) to another fragment.

public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

            String smsBody = smsMessage.getMessageBody().toString();
            String phonenumber = smsMessage.getOriginatingAddress();

            smsMessageStr += "SMS From: " + phonenumber + "\n";
            smsMessageStr += smsBody + "\n";                                
        }                                                                  
    }
}
barbsan
  • 3,418
  • 11
  • 21
  • 28
vishnu
  • 21
  • 1
  • 3
  • `Intent intent1 = new Intent(context, MainActivity.class);
    intent1.putExtra("phonenumber", address); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); context.sendBroadcast(intent1);`
    – vishnu Nov 13 '18 at 06:58
  • the above worked me for sending data from receiver to Activity but I am stuck with sending it to fragment – vishnu Nov 13 '18 at 06:59

2 Answers2

0

Just register another Broadcast receiver in your Fragment. Note code below works when your Fragment is attached to Activity and are in foreground.

If you want to send data to Fragment when your app is not running you will need to show notification on status bar and attach your data in pendingIntent of notification. As a target you need to specify your Activity class that holds Fragment of interest and then manually extract data in Activity's onCreate and pass it to Fragment.

In your Fragment:

// receiver as a global variable in your Fragment class
private BroadcastReceiver messagesReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getExtras() != null) {
            String smsMessageStr = intent.getExtras().getString("smsMessageStr");
            if (smsMessageStr != null && ! smsMessageStr()) {
                // do what you need with received data
            }
        }
    }
};

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    // ...
}

@Override
public void onResume() {
    super.onResume();
    if (getActivity() != null) {
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(messagesReceiver,
                new IntentFilter("your_intent_filter"));
    }
}

@Override
public void onPause() {
    super.onPause();
    if (getActivity() != null) {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(messagesReceiver);
    }
}

The reason we register and unregister Broadcast receiver in onResume and onPause methods is because we don't want Fragment to receive data and act upon that when is it being in foreground. More in this link

In your BroadcastReceiver:

public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

            String smsBody = smsMessage.getMessageBody().toString();
            String phonenumber = smsMessage.getOriginatingAddress();

            smsMessageStr += "SMS From: " + phonenumber + "\n";
            smsMessageStr += smsBody + "\n";   

            // send data only if we have smsMessageStr
            Intent newIntent = new Intent("your_intent_filter");
            newIntent.putExtra("smsMessageStr", smsMessageStr);
            LocalBroadcastManager.getInstance(this).sendBroadcast(newIntent);                             
        }                                                                  
    }
}
Marat
  • 6,142
  • 6
  • 39
  • 67
  • it may sound silly , is this my intent filter name **android.provider.Telephony.SMS_RECEIVED** ` ` – vishnu Nov 13 '18 at 08:11
  • because i recieve only null value @Marat -Marat – vishnu Nov 13 '18 at 08:14
  • Can you help me to find intent filter name ? because i am getting null value – vishnu Nov 13 '18 at 08:21
  • No, it is separate Broadcast receiver, hence with separate IntentFilter. As you can see from my code it is just a string. Just change the words inside of "" to whatever you want. – Marat Nov 13 '18 at 08:38
  • Nope, Still getting null Value – vishnu Nov 13 '18 at 19:37
  • can you please share code how to send data from receiver and get same data in activity , i need it very badly please @Marat – vishnu Nov 13 '18 at 19:39
  • @vishnu I've updated my answer and you can take a look at it. It is not difficult at all to implement what you are trying to achieve. Just pay attention to the code and try to understand it. You can use `Log` to track the process and find at what step problem occurs that leads to `null` values. – Marat Nov 14 '18 at 08:35
-1

There can be two approaches to send data to Fragment in the current scenario.

Approach One:

You can register the BroadcastReceiver to the activity that is hosting the Fragment and after receiving the Data in onReceive() you can call the Fragment method from an Activity like below:

ExampleFragment fragment = (ExampleFragment)getFragmentManager().
findFragmentById(R.id.example_fragment);
fragment.<specific_function_name_of_that_fragment>();

Approach Two:

You can directly register the BroadcastReceiver in Fragment and then call the fragment method defined there like below:

private final BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          //receive your data here
        }
    };

and then in onCreateView() Register BroadcastReceiver in Fragment like this :

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadCastReceiver,
                new IntentFilter("YOUR.INTENT.FILTER"));

        return inflater.inflate(R.layout.fragment_sub_categories, container, false);
    }

and then in onDestroyView() unRegister BroadcastReceiver in Fragment like this :

@Override
    public void onDestroyView() {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadCastReceiver);
        super.onDestroyView();
    }

Keep In Mind:

Fragment lifecycle will play an important role here. For receiving the Broadcast your Fragment needs to be Created and visible to the User. When Fragment will be destroyed or not Visible to the User then you won't receive the Broadcast.

Muhammad waris
  • 314
  • 1
  • 10