Search code examples
androidbroadcastreceiverblocking

Is BroadcastReceiver asynchronous enough to make this work


Wanted to stop a thread doing some downloads.
The code below work fine when i only have the stopNow = true; and no blocking occur.
I create the boolean stopNow = false; as a field in my IntentService.

Since stopNow only work when the connection is ongoing in the while loop
but it does not work if f.ex connection stales and start to block.

I wanted to add this code to really stop the blocking.

if(socket != null){
    socket.shutdownOutput();
    socket.shutdownInput();
}

The question is if this is asynchronous so if the execution is ongoing in the
while loop the stopNow = true; will stop it and i can put a sleep(5000) after the stopNow = true; and then the if(socket != null) will be true only if the stopNow had no effect.

hope you follow me..

BroadcastReceiver that are located inside the run():

private class MyIncomingListener extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(Consts.COM_CARLSBERG_STOPOUTGOING)) {
            String b = intent.getStringExtra(Consts.COM_CARLSBERG_BATCHUUID);
            if(b != null){
                if(b.equals(batch.batchUuid)){
                    stopNow = true;
                    // sleep(5000) wait for stopNow to take effect
                    // if socket=null then stopNow did it's job
                    // if socket is alive then there is blocking to unblock
                try{
                    if(socket != null){
                        socket.shutdownOutput();
                        socket.shutdownInput();
                    }
                } catch (Exception e) {}
               }    
            }
        }
    }
}

Solution

  • this is actually working good so far

        stopNow = true;
    
    try{
        if(socket != null){
            socket.shutdownOutput();
            socket.shutdownInput();
        }
    } catch (Exception e) {}