我在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();
}
}
}
什么错了?我调试和setChanged时调用notifyObservers方法,但是不要输入Observer的更新方法..