gpt4 book ai didi

android - 此消息无法回收,因为它仍在使用中

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:42:31 28 4
gpt4 key购买 nike

我正在尝试使用 this article创建异步 UDP 套接字。

所以我有这段代码:

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpThread
extends HandlerThread {

private static final String TAG = "UDP";
private final Handler uiHandler, workerHandler;
private final DatagramSocket socket = new DatagramSocket();

public UdpThread(final Handler uiHandler, final String hostname, final int port) throws SocketException {
super(TAG);
this.uiHandler = uiHandler;
start();
workerHandler = new Handler(getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(final Message msg) {
/*
if (msg.what == port && msg.obj == hostname) {
final InetSocketAddress address = new InetSocketAddress(hostname, port);
Log.d(TAG, "Connecting to " + address);
try {
socket.connect(address);
} catch (SocketException se) {
throw new RuntimeException(se);
}
}
*/
msg.recycle(); //java.lang.IllegalStateException: This message cannot be recycled because it is still in use.
return true;
}
});
workerHandler.obtainMessage(port, hostname).sendToTarget();
}
}

但是当我运行代码时,我得到了提到的 java.lang.IllegalStateException: This message cannot be recycled because it is still in use. 在尝试回收消息时。为什么会这样,如何解决它并防止内存泄漏?

最佳答案

首先让我们看看 Message recycle() 方法是如何工作的。

public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}

如果它正在使用中,您将得到 IllegalStateException

isInUse() 只是检查标志,看起来像:

boolean isInUse() {
return ((flags & FLAG_IN_USE) == FLAG_IN_USE);
}

当我们尝试阅读有关该标志的信息时,我们会看到描述:

If set message is in use.

This flag is set when the message is enqueued and remains set while it is delivered and afterwards when it is recycled. The flag is only cleared when a new message is created or obtained since that is the only time that applications are allowed to modify the contents of the message.

It is an error to attempt to enqueue or recycle a message that is already in use.

那么我们有什么

  1. 您不能回收邮件,直到它“正在使用”
  2. 在获得或创建新消息之前一直处于“使用中”状态

如何解决问题

在 Message 类中有方法 recycleUnchecked() 可以回收正在使用的消息对象even。这就是您所需要的!说明:

Recycles a Message that may be in-use.

Used internally by the MessageQueue and Looper when disposing of queued Messages.

最糟糕的是它在内部使用并具有包访问权限。当你打电话时它在内部使用的好东西:

handler.removeMessages(int what)

所以我想最终的解决方案是:

替换

msg.recycle();

try {
msg.recycle(); //it can work in some situations
} catch (IllegalStateException e) {
workerHandler.removeMessages(msg.what); //if recycle doesnt work we do it manually
}

关于android - 此消息无法回收,因为它仍在使用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44020010/

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