Registering and unregistering BroadcastReceiver in a fragment

AndroidAndroid FragmentsBroadcastreceiver

Android Problem Overview


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

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?

Android Solutions


Solution 1 - Android

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!!

Solution 2 - Android

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

Solution 3 - Android

OnResume Register:

context.registerReceiver(receiver,IntentFilter(BroadCastAction.action_success))

onPause unRegister :

context.unregisterReceiver(mContactBroadCastReceiver);

Solution 4 - Android

With Fragment, you will end up getting the exception Receiver not registered in some cases as in my case.

To resolve this, I used

 LocalBroadcastManager.getInstance(ctx).registerReceiver(myReceiver,IntentFilter(...))

instead of

 activity.registerReceiver(paxAmountReceiver,IntentFilter(...))

Similarly to unregister, use in onDestroyView() (For Eg.)

LocalBroadcastManager.getInstance(ctx).unregister(myReceiver)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNatashaView Question on Stackoverflow
Solution 1 - AndroidMehul JoisarView Answer on Stackoverflow
Solution 2 - AndroidStefan RonnkvistView Answer on Stackoverflow
Solution 3 - AndroidPradeep BishnoiView Answer on Stackoverflow
Solution 4 - AndroidAzizView Answer on Stackoverflow