Nik Myers
Nik Myers

Reputation: 1873

Broadcast receiver not working in some cases

So i have this receiver in my Fragment.class

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(WeekplanHepler.ACTION_SERVICE_BINDED) && getUpdateService() != null) {
            getCounts();
        }

        if (intent.getAction().equals(Helper.UpdateCounts)) {
            HashMap<String, Integer> counts = (HashMap<String, Integer>) intent.getSerializableExtra(Helper.PARAM_LIST_COUNTS);
            // Updating counts
        }
    }
};

For registering/uregistering this receiver i'm using this code:

@Override
public void onStart() {
    super.onStart();
    getCounts(true);
    getActivity().registerReceiver(receiver, getIntentFilter());
}

@Override
public void onStop() {
    super.onStop();
    getActivity().unregisterReceiver(receiver);
}

getCounts() is a RetrofitRequest puted in UpdateService, which is getUpdateService() here

So, when retrofit request has been finished, it returns counts through Intent and then, as you see, i'm updating them. But if i go to next Activity and then returns, request will work fine, and it will send intent, but receiver wont get it. I think this can be caused by method service is binded in first place. So i have BaseFragment, which binds service for all Fragments needed

public abstract class BaseFragment<T> extends CustomListFragment<T> {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().getApplicationContext().bindService(new Intent(getActivity().getApplicationContext(), 
                WeekplanUpdateService.class), connection, Context.BIND_AUTO_CREATE);
    }
}

When i go to next activity, it fragment will bind service, and my previous fragment will call request again, and will have counts. Maybe receiver has some limitations for how much he can get same intents, but i don't think so. Please help

Oh, i forgot to mention how i'm sending intent

sendBroadcast(new Intent(Helper.UpdateCounts).putExtra(Helper.PARAM_LIST_COUNTS, counts));

Upvotes: 0

Views: 207

Answers (1)

Nik Myers
Nik Myers

Reputation: 1873

So, when i've started to use

sendStickyBroadcast(new Intent(Helper.UpdateCounts)
                    .putExtra(Helper.PARAM_LIST_COUNTS, counts));

instead of

sendBroadcast(new Intent(Helper.UpdateCounts)
                    .putExtra(Helper.PARAM_LIST_COUNTS, counts));

it worked.

Upvotes: 1

Related Questions