Android : 如何更新由 class A 实现的接口方法并从 Class B 更新?

Android : how to update a interface method implemented by a class A and update from Class B?

我已经声明了一个名为

的接口
public interface listener {
    public void onError();
}

在 class A 中实现了这个接口。 我有另一个服务 B,我通过 startService(new Intent(this, B.class));

打开

现在的愿望是,当我在 class B 中收到任何错误时使用该接口,可以在不使用广播的情况下通知 class A?

如果你的ActivityAServiceB在同一个进程,你可以用bindService(Intent intent, ServiceConnection conn, int flags)代替startService来启动服务。 conn 将是一个内部 class 就像:

private ServiceConnection conn = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mMyService = ((ServiceB.MyBinder) service).getService();
        mMyService.setListener(new Listener() {
            @Override
            public void onError() {
                // ...
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mMyService = null;
    }
};

mMyService 是您的 ServiceB.

的实例

ServiceB中,只需覆盖onBind:

public IBinder onBind(Intent intent) {
    return new MyBinder();
}

并在ServiceB中添加以下class:

public class MyBinder extends Binder {
    public ServiceB getService() {
        return ServiceB.this;
    }
}

另外,添加一个public方法:

public void setListener(Listener listener) {
    this.mListener = listener;
}

这样您就可以在 ServiceB 中通知 ActivityA,例如:

someMethod(){
    // ...
    mListener.onError();
}

ps: bindService 会是这样的:

this.bindService(intent, conn, Context.BIND_AUTO_CREATE);

别忘了

protected void onDestroy() {
    this.unbindService(conn);
    super.onDestroy();
}

希望对您有所帮助ps。