Java Observer问题

时间:2010-07-14 10:31:46

标签: java android observer-pattern

我在Android平台上用Java实现自己的观察者时遇到了一些麻烦。

我创建了一个类调用NetworkPathJni,它使用名为NetworkPathJniObserver的Observer接口类来通知其他对象发生更改。

以下是NetworkPathJni.java的代码


public class NetworkPathJni {

NetworkPathJniObserver networkPathJniObserver;

  public NetworkPathJni(NetworkPathJniObserver aObserver){

    networkPathJniObserver = aObserver;
    Log.d("Phone", "NetworkPathJni Created" );

  }

  public void NetworkPathStateChanged(int aAvailabilityState){
      Log.d("Phone", "NetworkPathStateChanged new state = " + aAvailabilityState );
      TAvailabilityState availabilityState = intToAvailability(aAvailabilityState);
      Log.d("Phone", "Is SipNetworkPath alive?" +  networkPathJniObserver.isAlive());
      networkPathJniObserver.NetworkPathStateChanged(availabilityState);
      Log.d("Phone", "NetworkPathStateChanged end" );
      Log.d("Phone", "Is SipNetworkPath alive? (2)" +  networkPathJniObserver.isAlive());

  }

以下是观察者的代码


public interface NetworkPathJniObserver {

void NetworkPathStateChanged(TAvailabilityState aAvailabilityState);

boolean isAlive();
}

观察者在名为SipNetworkPath

的类中实现如下
public class SipNetworkPath implements NetworkPathInterface, NetworkPathJniObserver{

NetworkPathObserverInterface observer;
NetworkPathJni networkPathJni;

public SipNetworkPath(NetworkPathObserverInterface aObserver){
    domainType = aDomainType;
    observer = aObserver;
    networkPathJni = new NetworkPathJni(this);
    Log.d("Phone", "SipNetworkPath created" );
}

//NetworkPathJniObserver

@Override
public void NetworkPathStateChanged(TAvailabilityState availabilityState) {
    Log.d("SipNetworkPath", "SipNetworkPath - Do networkpathstate changed!");
}

@Override
public boolean isAlive() {
    return true;

}

SipNetworkPath的实现如下


public class WifiNetworkPath extends SipNetworkPath{

public WifiNetworkPath(NetworkPathObserverInterface aObserver) {
    super(aObserver);
}

日志记录显示已创建NetworkPathJni和SipNetworkPath,并且调用了NetworkPathStateChanged(int aAvailabilityState)。

在该方法中,所有日志记录都会返回,但是在观察者中没有调用该方法,当我问“SipNetworkPath是否存活?”时,我得到了错误。在记录中。

观察者类是否会失去参考或某种东西,或者我的方式是否存在错误?

1 个答案:

答案 0 :(得分:2)

在方法NetworkPathStateChanged中,您对可用性状态一无所知。通常你会在内部存储它,如下所示:

private TAvailabilityState availablilityState = null; // or a more suiteable initial value
@Override
public void NetworkPathStateChanged(TAvailabilityState availabilityState) {
    this.availabilityState = availabilityState;
    Log.d("SipNetworkPath", "SipNetworkPath - Do networkpathstate changed!");
}

然后,在方法isAlive中,您将根据状态做出回应:

@Override
public boolean isAlive() {
    return availabilityState == TAvailabilityState.ALIVE; // <-- this is just a guess, I don't know this class or enum.  
}

在这种情况下(参考你的评论)NetworkPathJniObserver的另一个实现必须存在于某个地方,或者你仍然在类路径上有一个旧的类文件。仅仅因为:如果isAlive()方法返回false而源代码中的方法不能,那么必须是应用程序中的其他代码。

我会在方法中添加一些调试代码,以清楚地记录实际调用的实例。 (我的猜测是,最后编译的版本尚未部署......)