summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/asynctask/DownloadObserver.java
blob: 1c5003ab3691db73176b60eef3ddc44ff36320ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package de.danoeh.antennapod.asynctask;

import android.app.Activity;
import android.content.*;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.service.download.DownloadService;
import de.danoeh.antennapod.service.download.Downloader;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Provides access to the DownloadService's list of items that are currently being downloaded.
 * The DownloadObserver object should be created in the activity's onCreate() method. resume() and pause()
 * should be called in the activity's onResume() and onPause() methods
 */
public class DownloadObserver {
    private static final String TAG = "DownloadObserver";

    /**
     * Time period between update notifications.
     */
    public static final int WAITING_INTERVAL_MS = 3000;

    private volatile Activity activity;
    private final Handler handler;
    private final Callback callback;

    private DownloadService downloadService = null;
    private AtomicBoolean mIsBound = new AtomicBoolean(false);

    private Thread refresherThread;
    private AtomicBoolean refresherThreadRunning = new AtomicBoolean(false);


    /**
     * Creates a new download observer.
     *
     * @param activity Used for registering receivers
     * @param handler  All callback methods are executed on this handler. The handler MUST run on the GUI thread.
     * @param callback Callback methods for posting content updates
     * @throws java.lang.IllegalArgumentException if one of the arguments is null.
     */
    public DownloadObserver(Activity activity, Handler handler, Callback callback) {
        if (activity == null) throw new IllegalArgumentException("activity = null");
        if (handler == null) throw new IllegalArgumentException("handler = null");
        if (callback == null) throw new IllegalArgumentException("callback = null");

        this.activity = activity;
        this.handler = handler;
        this.callback = callback;
    }

    public void onResume() {
        if (BuildConfig.DEBUG) Log.d(TAG, "DownloadObserver resumed");
        activity.registerReceiver(contentChangedReceiver, new IntentFilter(DownloadService.ACTION_DOWNLOADS_CONTENT_CHANGED));
        connectToDownloadService();
    }

    public void onPause() {
        if (BuildConfig.DEBUG) Log.d(TAG, "DownloadObserver paused");
        try {
            activity.unregisterReceiver(contentChangedReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        try {
            activity.unbindService(mConnection);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        stopRefresher();
    }

    private BroadcastReceiver contentChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // reconnect to DownloadService if connection has been closed
            if (downloadService == null) {
                connectToDownloadService();
            }
            callback.onContentChanged();
            startRefresher();
        }
    };

    public interface Callback {
        void onContentChanged();

        void onDownloadDataAvailable(List<Downloader> downloaderList);
    }

    private void connectToDownloadService() {
        activity.bindService(new Intent(activity, DownloadService.class), mConnection, 0);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName className) {
            downloadService = null;
            mIsBound.set(false);
            stopRefresher();
            Log.i(TAG, "Closed connection with DownloadService.");
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadService = ((DownloadService.LocalBinder) service)
                    .getService();
            mIsBound.set(true);
            if (BuildConfig.DEBUG)
                Log.d(TAG, "Connection to service established");
            List<Downloader> downloaderList = downloadService.getDownloads();
            if (downloaderList != null && !downloaderList.isEmpty()) {
                callback.onDownloadDataAvailable(downloaderList);
                startRefresher();
            }
        }
    };

    private void stopRefresher() {
        if (refresherThread != null) {
            refresherThread.interrupt();
        }
    }

    private void startRefresher() {
        if (refresherThread == null || refresherThread.isInterrupted()) {
            refresherThread = new Thread(new RefresherThread());
            refresherThread.start();
        }
    }

    private class RefresherThread implements Runnable {

        public void run() {
            refresherThreadRunning.set(true);
            while (!Thread.interrupted()) {
                try {
                    Thread.sleep(WAITING_INTERVAL_MS);
                } catch (InterruptedException e) {
                    Log.d(TAG, "Refresher thread was interrupted");
                }
                if (mIsBound.get()) {
                    postUpdate();
                }
            }
            refresherThreadRunning.set(false);
        }

        private void postUpdate() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onContentChanged();
                    if (downloadService != null) {
                        List<Downloader> downloaderList = downloadService.getDownloads();
                        if (downloaderList == null || downloaderList.isEmpty()) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            });
        }
    }

    public void setActivity(Activity activity) {
        if (activity == null) throw new IllegalArgumentException("activity = null");
        this.activity = activity;
    }

}