anze87
anze87

Reputation: 253

How to update fragment tab from BroadcastReceiver?

I send intent when some flag in my program is set, and then receive this intent in BroadcastReceiver. I don't know how to update tab fragment from here. Any suggestions or examples?

I get this log when flag is set, but I don't knw how from there:

public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      Toast.makeText(context, "hello :)", Toast.LENGTH_LONG).show();
   }  
}

Thanks for help!

Fragment:

public class FragmentInfo extends Fragment {

private TextView textView1;
    private TextView textView3;
    private TextView textView5;
    private TextView textView7;
    private TextView textView8;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View myFragmentView = inflater.inflate(R.layout.fragment_info, container, false);

    connectButton = (Button) myFragmentView.findViewById(R.id.button1);
    changeSettingsButton = (Button) myFragmentView.findViewById(R.id.button2);
    erraseFlightsButton = (Button) myFragmentView.findViewById(R.id.button3);

    //TextView for status of connected device..
    textView1 = (TextView)myFragmentView.findViewById(R.id.TextView1);
    //TextView for Device name
    textView3 = (TextView)myFragmentView.findViewById(R.id.TextView3);
    //TextView for Serial number
    textView5 = (TextView)myFragmentView.findViewById(R.id.TextView5);
    //TextView for Software version
    textView7 = (TextView)myFragmentView.findViewById(R.id.TextView7);
    //TextView for Connected Device version
    textView8 = (TextView)myFragmentView.findViewById(R.id.TextView8);  


    return myFragmentView;
}

}

Upvotes: 1

Views: 1584

Answers (1)

Joel Bodega
Joel Bodega

Reputation: 644

  1. Make the Receiver class a nested class of one that controls the tabs. This way you should have access to the methods that refresh data through fragment's methods. This receiver should be registered and unregistered in onStart() and onPause() respectively (wrap those in a try-catch block as some versions of Android may crash at registering or unregistering). This receiver should be a nested class of the activity class that controls your fragments. Don't put it in the fragment class itself.

  2. Make it a top level class and pass a listener through a method like setUpdateListener(YourListener). Implement the listener in the activity that controls the tabs.

  3. There's also the Messengerclass which you could pass to communicate intra processes.

EDIT: Either way with the receiver that updates fragments, don't register it in the manifest but through code. No need to have a receiver, that updates UI, triggered when there is no UI showed.

Upvotes: 3

Related Questions