Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 469
Natasha Avatar asked May 17 '13 19:05

Natasha


People also ask

Where do I register and unregister broadcast receiver?

You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().

Is it necessary to unregister BroadcastReceiver?

It's always suggested to register and unregister broadcast receiver programmatically as it saves system resources.

When would you use a BroadcastReceiver?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.


2 Answers

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

like image 95
Mehul Joisar Avatar answered Oct 23 '22 16:10

Mehul Joisar


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

like image 17
Stefan Ronnkvist Avatar answered Oct 23 '22 16:10

Stefan Ronnkvist