How to send a data from a broadcast receiver to fragment?












1















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";
}
}
}









share|improve this question

























  • Intent intent1 = new Intent(context, MainActivity.class);<br/> intent1.putExtra("phonenumber", address); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); context.sendBroadcast(intent1);

    – vishnu
    Nov 13 '18 at 6: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 6:59
















1















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";
}
}
}









share|improve this question

























  • Intent intent1 = new Intent(context, MainActivity.class);<br/> intent1.putExtra("phonenumber", address); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); context.sendBroadcast(intent1);

    – vishnu
    Nov 13 '18 at 6: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 6:59














1












1








1








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";
}
}
}









share|improve this question
















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";
}
}
}






android android-fragments broadcastreceiver android-broadcast android-broadcastreceiver






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 8:59









barbsan

2,22811222




2,22811222










asked Nov 13 '18 at 6:56









vishnuvishnu

62




62













  • Intent intent1 = new Intent(context, MainActivity.class);<br/> intent1.putExtra("phonenumber", address); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); context.sendBroadcast(intent1);

    – vishnu
    Nov 13 '18 at 6: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 6:59



















  • Intent intent1 = new Intent(context, MainActivity.class);<br/> intent1.putExtra("phonenumber", address); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); context.sendBroadcast(intent1);

    – vishnu
    Nov 13 '18 at 6: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 6:59

















Intent intent1 = new Intent(context, MainActivity.class);<br/> intent1.putExtra("phonenumber", address); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); context.sendBroadcast(intent1);

– vishnu
Nov 13 '18 at 6:58







Intent intent1 = new Intent(context, MainActivity.class);<br/> intent1.putExtra("phonenumber", address); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); context.sendBroadcast(intent1);

– vishnu
Nov 13 '18 at 6: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 6:59





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 6:59












2 Answers
2






active

oldest

votes


















0














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.






share|improve this answer































    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);
    }
    }
    }





    share|improve this answer


























    • it may sound silly , is this my intent filter name android.provider.Telephony.SMS_RECEIVED <receiver android:name=".MySMS_Reader"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

      – vishnu
      Nov 13 '18 at 8:11













    • because i recieve only null value @Marat -Marat

      – vishnu
      Nov 13 '18 at 8:14













    • Can you help me to find intent filter name ? because i am getting null value

      – vishnu
      Nov 13 '18 at 8: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 8:38











    • @vishnu Were you able to solve your problem?

      – Marat
      Nov 13 '18 at 18:16











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53275423%2fhow-to-send-a-data-from-a-broadcast-receiver-to-fragment%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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.






    share|improve this answer




























      0














      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.






      share|improve this answer


























        0












        0








        0







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 '18 at 7:50









        Muhammad warisMuhammad waris

        13717




        13717

























            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);
            }
            }
            }





            share|improve this answer


























            • it may sound silly , is this my intent filter name android.provider.Telephony.SMS_RECEIVED <receiver android:name=".MySMS_Reader"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

              – vishnu
              Nov 13 '18 at 8:11













            • because i recieve only null value @Marat -Marat

              – vishnu
              Nov 13 '18 at 8:14













            • Can you help me to find intent filter name ? because i am getting null value

              – vishnu
              Nov 13 '18 at 8: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 8:38











            • @vishnu Were you able to solve your problem?

              – Marat
              Nov 13 '18 at 18:16
















            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);
            }
            }
            }





            share|improve this answer


























            • it may sound silly , is this my intent filter name android.provider.Telephony.SMS_RECEIVED <receiver android:name=".MySMS_Reader"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

              – vishnu
              Nov 13 '18 at 8:11













            • because i recieve only null value @Marat -Marat

              – vishnu
              Nov 13 '18 at 8:14













            • Can you help me to find intent filter name ? because i am getting null value

              – vishnu
              Nov 13 '18 at 8: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 8:38











            • @vishnu Were you able to solve your problem?

              – Marat
              Nov 13 '18 at 18:16














            0












            0








            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);
            }
            }
            }





            share|improve this answer















            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);
            }
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 14 '18 at 8:32

























            answered Nov 13 '18 at 7:19









            MaratMarat

            1,87541333




            1,87541333













            • it may sound silly , is this my intent filter name android.provider.Telephony.SMS_RECEIVED <receiver android:name=".MySMS_Reader"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

              – vishnu
              Nov 13 '18 at 8:11













            • because i recieve only null value @Marat -Marat

              – vishnu
              Nov 13 '18 at 8:14













            • Can you help me to find intent filter name ? because i am getting null value

              – vishnu
              Nov 13 '18 at 8: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 8:38











            • @vishnu Were you able to solve your problem?

              – Marat
              Nov 13 '18 at 18:16



















            • it may sound silly , is this my intent filter name android.provider.Telephony.SMS_RECEIVED <receiver android:name=".MySMS_Reader"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

              – vishnu
              Nov 13 '18 at 8:11













            • because i recieve only null value @Marat -Marat

              – vishnu
              Nov 13 '18 at 8:14













            • Can you help me to find intent filter name ? because i am getting null value

              – vishnu
              Nov 13 '18 at 8: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 8:38











            • @vishnu Were you able to solve your problem?

              – Marat
              Nov 13 '18 at 18:16

















            it may sound silly , is this my intent filter name android.provider.Telephony.SMS_RECEIVED <receiver android:name=".MySMS_Reader"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

            – vishnu
            Nov 13 '18 at 8:11







            it may sound silly , is this my intent filter name android.provider.Telephony.SMS_RECEIVED <receiver android:name=".MySMS_Reader"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

            – vishnu
            Nov 13 '18 at 8:11















            because i recieve only null value @Marat -Marat

            – vishnu
            Nov 13 '18 at 8:14







            because i recieve only null value @Marat -Marat

            – vishnu
            Nov 13 '18 at 8:14















            Can you help me to find intent filter name ? because i am getting null value

            – vishnu
            Nov 13 '18 at 8:21





            Can you help me to find intent filter name ? because i am getting null value

            – vishnu
            Nov 13 '18 at 8: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 8:38





            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 8:38













            @vishnu Were you able to solve your problem?

            – Marat
            Nov 13 '18 at 18:16





            @vishnu Were you able to solve your problem?

            – Marat
            Nov 13 '18 at 18:16


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53275423%2fhow-to-send-a-data-from-a-broadcast-receiver-to-fragment%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()