Nikhil Nikhil - 2 years ago 106
Android Question

LocalBroadcastManager onReceive() not called

This is what I'm doing :

I'm sending an intent from

MainActvity
to my
Fragment
using
LocalBroadcastManager
. I wrote the
onReceive()
code in
onCreateView()
of the Fragment class. I'm unregistering the Receiver in
onDestroy()
.

But
onReceive()
is not getting called. Why?

In MainActivity class :

void handleText()
{
Intent i = new Intent("receiveURL");
i.putExtra("key", sharedText);

this.sendBroadcast(i);
}


In my Fragment class :

public class AddTab extends Fragment implements View.OnClickListener {

BroadcastReceiver receiver;

EditText textBox;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

}

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

// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_add, container, false);

textBox = (EditText) view.findViewById(R.id.editText);

receiver = new BroadcastReceiver() {
//This is not getting called
@Override
public void onReceive(Context context, Intent intent) {
String g = intent.getStringExtra("key");
textBox = (EditText) getView().findViewById(R.id.editText);
if (textBox != null){
textBox.setText(g);}
else{
Log.d("NULL", "");
}

Log.d("received","");
}
};

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("receiveURL"));
...
//some code
}


public void onDestroy() {


super.onDestroy();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
}

}


Why is that receiver is not getting called? Any help please?

Answer Source

You are using this.sendBroadcast(i) which sends a global, inter-app broadcast that will not be received by a LocalBroadcastManager.

In your MainActivity, replace

this.sendBroadcast(i);

with

LocalBroadcastManager.getInstance(this).sendBroadcast(i);

This will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download