Aggressor
Aggressor

Reputation: 13551

Service Fires Hundreds Of Time On Single Broadcast

I am sending a broadcast from an activity to a service:

Activity:

        Timber.d("SENDING REQUEST");
        // Send broadcast to service to request GPS (this avoids concurrency issues with file collision)
        Intent updateActivitiesRequest = new Intent(A_GPS.UPDATE_ACTIVITIES_REQUEST);
        sendBroadcast(updateActivitiesRequest);

Service:

@Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        startService(intent);

        _updateRequestReciever = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                Log.d(TAG, "GOT IT");
               // broadcastSavedActivityDataForToday();
            }
        };

        IntentFilter intentFilter = new IntentFilter(A_GPS.UPDATE_ACTIVITIES_REQUEST);
        registerReceiver(_updateRequestReciever, intentFilter);

        return START_NOT_STICKY;
    }

However, when the request is fired once, I get hundreds of fires from the onReceive in my service:

D/A_GPS: SENDING REQUEST

D/S_GPS: GOT IT

D/S_GPS: GOT IT

D/S_GPS: GOT IT

D/S_GPS: GOT IT

...and hundreds more

It fires so many times in fact my logcat cant even process it and I get a range of errors flooding the console. Some of the errors I get when I tried to send my response are are:

  1. Failed Transaction Binder (and !! FAILED TRANSACTION BINDER !!)
  2. Failure sending broadcast result of Intent {} android.os.DeadObjectException
  3. TransactionTooLargeException

Clearly this is a result of it trying to send a reply when I uncomment broadcastSavedActivityDataForToday() and it turns out to be hundreds of replies.

Do you have any idea why my broadcast receiver in my service is firing hundreds of times from a single broadcast intent?

Upvotes: 0

Views: 98

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007534

Two reasons:

  1. Your service is calling startService() on itself from onStartCommand(). This is what we call an "infinite loop". Do not do this.

  2. You are registering the receiver in onStartCommand(), and so will register one for every startService() call. Register the receiver once in onCreate().

Upvotes: 1

Related Questions