-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTaskObserver.java
73 lines (60 loc) · 1.58 KB
/
TaskObserver.java
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
package propoid.util.service;
import propoid.util.service.TaskService.ObserverBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
/**
* An observer of a {@link TaskService}.
*
* <pre>
* @code{
* FooObserver observer = new FooObserver() {
* public void onBar() {
* }
* };
* observer.subscribe(context, FooService.class);
* }
* </pre>
*
* An observer will always be notified on the main thread.
*/
@SuppressWarnings("rawtypes")
public abstract class TaskObserver implements ServiceConnection {
private Context context;
private ObserverBinder binder;
/**
* Subscribe with the given {@link TaskService}.
*/
public void subscribe(Context context, Class<? extends TaskService> service) {
if (this.context != null) {
throw new IllegalStateException();
}
this.context = context;
context.bindService(new Intent(context, service), this,
Context.BIND_AUTO_CREATE);
}
/**
* Unsubsribe from the previously subscribed {@link TaskService}.
*/
@SuppressWarnings("unchecked")
public void unsubscribe() {
if (binder == null) {
throw new IllegalStateException();
}
binder.unsubscribe(this);
binder = null;
context.unbindService(this);
context = null;
}
@SuppressWarnings("unchecked")
@Override
public final void onServiceConnected(ComponentName name, IBinder binder) {
this.binder = (ObserverBinder) binder;
this.binder.subscribe(this);
}
@Override
public final void onServiceDisconnected(ComponentName name) {
}
}