Custom changeable handler when a Service finishes downloading a file
<p>I have a Service that downloads a file from the internet.  What I want is for the response (an InputStream in this case) to be handled by a custom handler that can be switched (like a strategy pattern) but I can't figure out how to do this.</p>

<p>So basically the User of the API would be able to plug in different handlers for the response, some would parse XML, others might save files etc.</p>

<p>I realise I could pass through the activity context and execute the method from this (given some interface) but I don't want to do this obviously, in case the Activity is closed in the meantime while the file is still downloaded.</p>

<p>How might I do this?</p>

<p><strong>UPDATE - I just had one idea it will work sort of but has problem if the DownloadRunnable gets changed between executions of the downloads.</strong></p>

<p>The modified Runnable interface</p>

<pre><code>interface DownloadRunnable {
    void run(InputStream stream);
}
</code></pre>

<p>An enum</p>

<pre><code>public enum ServiceHandler {
    DOWNLOAD_HANDLER;

    private DownloadRunnable handler=null;

    /**Called from the Service*/
    public void doHandler(InputStream stream) {
        if(handler==null) throw new IllegalStateException("You must set the handler first: setDownloadHandler()");
        this.handler.run(stream);
    }

     /**Set before theservice runs*/
     public void setHandler(DownloadRunnable r) {
         this.handler = r;
     }
}
</code></pre>

<p>The client can set what happens for each enum</p>

<pre><code>ServiceHandler.DOWNLOAD_HANDLER.setHandler(new DownloadRunnable() {

        @Override
        public void run(InputStream stream) {
            // The user can do anything they want with the stream
        }
    });
</code></pre>

<p>The Service runs this when the input stream is available</p>

<pre><code>ServiceHandler.DOWNLOAD_HANDLER.doHandler(stream);
</code></pre>

<p>This kind of works but is not so elegant.</p>

<ol>
<li><p>What if the user runs the same operation twice with different DownloadRunnables set (before the first is complete)</p></li>
<li><p>The user has to set the Handler first is a separate enum object (not so user friendly or intuitive).</p></li>
<li><p>Maybe I could create a Map of DownloadRunnables each with an ID (static field - auto increment) that gets passed back and the correct runnable can then get executed...but all this is getting more complex than I had hoped.</p></li>
</ol>
