0

I declared the following receiver in my app's Main Activity's onCreate()

I send the broadcast UpdaterService.BROADCAST_ACTION_STATE_CHANGE from the UpdaterService IntentService (code below).

But I send this broadcast only twice once just after UpdaterService starts and once after it finishes, both from UpdaterService only.

The problem: Yet in the log message "misrefreshing: ...." is printed 3 times. The last two times are understandable. But the first time log message is: "misrefreshing: false", which is unexpected if you read the code.

Inside MainActivity#onCreate :

mRefreshingReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (UpdaterService.BROADCAST_ACTION_STATE_CHANGE.equals(intent.getAction())) {
                mIsRefreshing = intent.getBooleanExtra(UpdaterService.EXTRA_REFRESHING, false);
                updateRefreshingUI();
                Log.i("haha","misrefreshing: " + mIsRefreshing);
                mPagerAdapter.notifyDataSetChanged();
            }
        }
    };

UpdaterService class:

public class UpdaterService extends IntentService {
    private static final String TAG = "UpdaterService";

    public static final String BROADCAST_ACTION_STATE_CHANGE
        = "com.example.xyzreader.intent.action.STATE_CHANGE";
    public static final String EXTRA_REFRESHING
        = "com.example.xyzreader.intent.extra.REFRESHING";

public UpdaterService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {

    //check for network connectivity

    sendStickyBroadcast(
            new Intent(BROADCAST_ACTION_STATE_CHANGE).putExtra(EXTRA_REFRESHING, true));

    for (String category : categories) {
        try {
            JSONObject rootJson = RemoteEndpointUtil.fetchJson(category);
            if(rootJson == null) {
                sendStickyBroadcast(
                        new Intent(BROADCAST_ACTION_STATE_CHANGE).putExtra(EXTRA_REFRESHING, false));
                return;
            }

            //enter data into database... removed for Stackoverflow readability

            getContentResolver().applyBatch(ItemsContract.CONTENT_AUTHORITY, cpo);

        } catch (JSONException | RemoteException | OperationApplicationException e) {
            Log.e(TAG, "Error updating content.", e);
        }
    }

    sendStickyBroadcast(
            new Intent(BROADCAST_ACTION_STATE_CHANGE).putExtra(EXTRA_REFRESHING, false));
   }
}
vaibhavdj
  • 21
  • 3
  • Any particular reason you're sending a sticky broadcast? That would be why it's firing an extra time, when you register the Receiver. – Mike M. Apr 09 '18 at 21:14
  • I tried replacing Sticky Broadcast with Broadcast but got the same result. – vaibhavdj Apr 09 '18 at 21:25
  • It's still "stuck" from the previous broadcasts. You'll need to either remove those sticky broadcasts programmatically, or uninstall/reinstall your app. – Mike M. Apr 09 '18 at 21:28

0 Answers0