【发布时间】:2014-04-09 23:45:02
【问题描述】:
我已经在 android 应用程序中实现了 Observer/Observable 模式,但是当通知时,接收者没有接到电话。
这是我的代码:
观察者,是一个调用休息服务的类,如果由于服务器关闭或其他问题导致调用失败,我更改休息服务器ip,从Observable增加一个int值,并且Observable必须调用我的更新覆盖方法,但不要这样做:
public class LoginApiCall extends ApiCallBase<Object> implements Observer {
private String team;
private String password;
private String deviceId;
private LoginIntents loginIntents;
public LoginApiCall(Context context, String team, String password, String deviceId, ApiResponseListener listener) {
super(context, listener);
this.team = team;
this.password = password;
this.deviceId = deviceId;
loginIntents = LoginIntents.getInstance();
loginIntents.addObserver(this);
}
@Override
protected void doWork() {
LoginData login = new LoginData(team, password, deviceId);
Gson gson = new Gson();
String value = gson.toJson(login);
try {
ByteArrayEntity entity = new ByteArrayEntity(value.getBytes("UTF-8"));
Api.post(context, "teamLogin", entity, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
apiSuccess(jsonObject);
}
@Override
public void onFailure(Throwable throwable, JSONObject jsonObject) {
throwable.printStackTrace();
apiError(new ApiException());
}
@Override
public void onFailure(Throwable throwable, String content) {
if (throwable.getCause() instanceof ConnectTimeoutException) {
System.out.println("Connection timeout !");
}
loginIntents.increaseIntents();
throwable.printStackTrace();
apiError(new ServerException());
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void update(Observable observable, Object data) {
execute();
}
}
这就是 Observable,当 Intents 属性从 0 增加到 1 时,通知观察者,他们应该做点什么:
public class LoginIntents extends Observable {
private static volatile LoginIntents instance = null;
private int intents = 0;
private LoginIntents() {
}
public static LoginIntents getInstance() {
if (instance == null) {
instance = new LoginIntents();
}
return instance;
}
public int getIntents() {
return instance.intents;
}
public void increaseIntents() {
instance.intents++;
if (intents == 1) {
notifyObservers();
setChanged();
}
}
}
怎么了? notifyObservers 方法在我调试时被调用,setChanged 也被调用,但不要进入 Observer 的更新方法..
【问题讨论】:
标签: android design-patterns observable