javaandroidandroid-fragmentsbroadcastreceiverintentservice

How to set broadcast listener interface in fragment?


I have service, which gets data from API and sends this data to BroadcastReceiver class. Also, I create interface OnReceiveListener, which used in Activity. Look at the code here:

Activity:

public class StartActivity extends AppCompatActivity
    implements MyBroadcastReceiver.OnReceiveListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    MyBroadcastReceiver receiver = new MyBroadcastReceiver();
    receiver.setOnReceiveListener(this);
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
            new IntentFilter(MyBroadcastReceiver.START));
    ...
}

@Override
public void onReceive(Intent intent) {
    // Do smth here
}
}

MyBroadcastReceiver:

public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String START = "com.example.myapp.START";
public static final String GET_LINKS = "com.example.myapp.GET_LINKS";

private OnReceiveListener onReceiveListener = null;

public interface OnReceiveListener {
    void onReceive(Intent intent);
}

public void setOnReceiveListener(Context context) {
    this.onReceiveListener = (OnReceiveListener) context;
}

@Override
public void onReceive(Context context, Intent intent) {
    if(onReceiveListener != null) {
        onReceiveListener.onReceive(intent);
    }
}
}

Service isn't important on this question.

---- Question ----

So, what's problem: I want to use this receiver in fragment, but when it sets context - I get exception "enable to cast". What I should to do on this case?

Here is my code in fragment:

public class MainFragment extends Fragment
    implements MyBroadcastReceiver.OnReceiveListener {

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
    myBroadcastReceiver.setOnReceiveListener(getContext());
    LocalBroadcastManager.getInstance(getContext()).registerReceiver(myBroadcastReceiver,
            new IntentFilter(MyBroadcastReceiver.GET_LINKS));
}

@Override
public void onReceive(Intent intent) {
    // Do smth here
}
}

Solution

  • Your MainFragment class implements your OnReceiveListener interface, not its Context as returned by getContext(). Instead of passing a Context object into setOnReceiveListener(), try directly passing an OnReceiveListener instance. Then your fragment and activity can both call setOnReceiveListener(this).