public abstract class ReadingTask extends Observable {
private State state;
/**
* Construct a reading task .
*
*/
public ReadingTask() {
this.state = State.Prepared;
addObserver(new StateChangeObserver());
}
public abstract void doInBackground();
public void onPreExcuted() {
}
public void onPostExcuted() {
}
/**
* Return the task's state .
*
* @return task's state .
*/
public State getState() {
return state;
}
/**
* Remove the observers of the reading task , and clear all the state change
* listeners .
*/
public void clear() {
deleteObservers();
}
/**
* Set the task's state .
*
* @param state
* task's state .
*/
void setState(State state) {
this.state = state;
}
/**
* Start to do the task's action . If the task is to cancel the jni
* operation , its started state is set Canceled .
*/
void start() {
state = State.Started;
setChanged();
notifyObservers();
try {
doInBackground();
} catch (Exception e) {
state = State.Failed;
setChanged();
notifyObservers(e);
}
state = State.Finished;
setChanged();
notifyObservers();
}
/**
* Enum the state of the task , it contains Prepared , Started , Canceled ,
* Failed , Finished .
*
* @author zouyuefu
*/
public static enum State {
Prepared, Started, Canceled, Failed, Finished
}
/**
* An observer is used to notify the task when its state changed .
*
* @author zouyuefu
*/
private static class StateChangeObserver implements Observer {
public void update(Observable observable, Object data) {
if (observable instanceof ReadingTask) {
ReadingTask task = (ReadingTask) observable;
Log.d("debug", "state : " + task.getState()
+ " --return value:" + data);
if (task.state == State.Started) {
Message.obtain(ReadingWorker.getInstance().getHandler(),
ReadingWorker.MESSAGE_TASK_STARTED, task)
.sendToTarget();
} else if (task.state == State.Finished) {
Message.obtain(ReadingWorker.getInstance().getHandler(),
ReadingWorker.MESSAGE_TASK_FINISHED, task)
.sendToTarget();
}
}
}
}
}
这个例子的核心是为了写一个观察者,让前后的操作在主线程中进行进行(前后做state = State.Started;setChanged();notifyObservers();和state = State.Finished;setChanged();notifyObservers();这个的改变会影响StateChangeObserver ,然后StateChangeObserver 会通知handle,handle会做相应的处理),而doInBackground();是在背景线程中做事