Registering and unregistering BroadcastReceiver in a fragment

My app has an action bar with 3 fragment tabs.
In the second fragment I register and unregister a BroadcastReceiver.
I unregister the receiver in onPause and register it in onCreateView and in onResume.

getActivity().registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

and

  • Nested Fragments using support library v4 revision 11
  • IntentService won't show Toast
  • Adding screen brightness controls to android application
  • Unexpected resume of “package name” while already resumed in ''package name" Error in Android
  • Google Analytics V2 not recording stats from Android app
  • Download file inside WebView
  • getActivity().unregisterReceiver(batteryInfoReceiver);
    

    1) Is it all right to register the same reciever twice (in onCreateView and onResume)?(is it harmless?)

    2) Is it enough to just register the reciever in onResume?

  • How to convert DP, PX, SP among each other, especially DP and SP?
  • Android WebView for Facebook Like Button
  • How to programmatically set drawableRight on Android Edittext?
  • Android Studio: Module won't show up in “Edit Configuration”
  • What is different between getContext and getActivity from Fragment in support library?
  • how to create ripple effect for pre-lollipop
  • 2 Solutions collect form web for “Registering and unregistering BroadcastReceiver in a fragment”

    Have a look at life-cycle of Fragments:

    onCreateView():
    The system calls this when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI.

    onResume():
    The fragment is visible in the running activity

    onPause():
    This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

    Conclusion:

    So it is better to register the receiver only inside onResume() and unregister inside onPause() because onCreateView() deals with view hierarchy only. It has nothing to do with receiver. So it is not harmful but surely it is useless.

    I hope it will be helpful!!

    Here is code that works for me:

    Inside layout:

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sendInternalBroadcast"
        android:text="Broadcast"/>
    

    Fragment Layout:

        <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:gravity="center">
    
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Fragment One"
            android:id="@+id/fragmentoneTextView1"/>
    
    </LinearLayout>
    

    inside Main Activity:

        public void sendInternalBroadcast(View view)
    {
        Intent intent = new Intent();
    intent.setAction("com.codingbadly.stefanronnkvist.simplebroadcastreceiver.setup");
        intent.putExtra("From", "sendInternalBroadcast");
        sendBroadcast(intent);
    }
    

    Fragment:

    import android.app.*;
    import android.content.*;
    import android.os.*;
    import android.view.*;
    import android.widget.*;
    
    public class FragmentOne extends Fragment
    {
        View view;
        Context _context;
        PendingIntent pi;
        BroadcastReceiver br;
        AlarmManager am;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            view = inflater.inflate(R.layout.fragmentone, container, false);
            setup();
            return view;
        }
    
        @Override
        public void onAttach(Context context)
        {
            super.onAttach(context);
            _context = context;
        }
    
        @Override
        public void onDestroyView()
        {
            super.onDestroyView();
            _context.unregisterReceiver(br);
        }
    
    
        private void setup()
        {
            br = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent i)
                {
                    TextView tv = (TextView)view.findViewById(R.id.fragmentoneTextView1);
                    tv.setText("onReceive");
                }
            };
            _context.registerReceiver(br, new IntentFilter("com.codingbadly.stefanronnkvist.simplebroadcastreceiver.setup"));
            pi = PendingIntent.getBroadcast(_context, 0, new Intent("com.codingbadly.stefanronnkvist.simplebroadcastreceiver.setup"), 0);
            am = (AlarmManager)(_context.getSystemService(Context.ALARM_SERVICE));
        }
    }
    

    Good Luck..
    Stefan Ronnkvist

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.