gpt4 book ai didi

android - Netty 框架或如何将其与 AsyncTask 一起使用

转载 作者:太空狗 更新时间:2023-10-29 15:17:51 24 4
gpt4 key购买 nike

我正在尝试开发一个将使用 Netty 的 Android 应用程序.

首先我想在Android上测试Netty,所以我要开发EchoClient示例。

我正在“翻译”客户端部分。这部分有两个类:EchoClientEchoClientHandler

EchoClient 作为线程运行,EchoClientHandler 处理所有网络内容。

在 main 方法中,EchoClient 是这样运行的:

new EchoClient(host, port, firstMessageSize).run();

EchoClientHandler 使用异步事件编程模型。

这是EchoClient的一段代码:

public void run() {
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));

// Set up the pipeline factory.
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
new EchoClientHandler(firstMessageSize));
}
});

// Start the connection attempt.
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

// Wait until the connection is closed or the connection attempt fails.
future.getChannel().getCloseFuture().awaitUninterruptibly();

// Shut down thread pools to exit.
bootstrap.releaseExternalResources();
}

run() 方法可以是AsyncTask.doBackground() 方法。

如你所见EchoClientHandler是这个类的一部分。

这是 EchoClientHandler我想在 UI 线程中使用的方法:

@Override
public void messageReceived(
ChannelHandlerContext ctx, MessageEvent e) {
// Send back the received message to the remote peer.
transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
e.getChannel().write(e.getMessage());
}

如何在 AsynTask 中使用 EchoClientHandler?当调用 messageReceived 时,我不知道如何在 onProgressUpdate 上更新 TextView。

有什么建议吗?

最佳答案

也许您可以使用回调。

第 1 步。定义接口(interface)

public interface MyCallback {
public void onMessage(string msg);
}

第二步在EchoHandler构造函数中获取一个符合该接口(interface)的对象并将其存储为类变量

private MyCallback _myCallback
public EchoClientHandler(int firstMessageSize, MyCallback callback) {
_myCallback = myCallback;
...
}

第 3 步。 将对象传递给管道中的构造函数。 myCallback 可以作为参数来自 run() 或在您的 EchoClient 构造函数中。

// Set up the pipeline factory.
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
new EchoClientHandler(firstMessageSize, myCallback));
}
})

第 4 步。在您的消息处理程序中调用回调

@Override
public void messageReceived(
ChannelHandlerContext ctx, MessageEvent e) {
// Send back the received message to the remote peer.
transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
e.getChannel().write(e.getMessage());

_myCallback.onMessage("message");
}

希望这对您有所帮助。

关于android - Netty 框架或如何将其与 AsyncTask 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10962654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com