gpt4 book ai didi

java - Android 异步任务和 TCP/IP 套接字

转载 作者:行者123 更新时间:2023-12-02 06:50:51 25 4
gpt4 key购买 nike

我有一个关于异步任务的基本问题。我是 Android 编程的初学者,很抱歉问这个问题。

我将在 doinbackground 中打开一个套接字。

  doInBackground(... ) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(192.168.0.1, 2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
}}

当 AsyncTask 完成时,套接字会发生什么? (一旦 doInBackground 和 OnPostExecute 过去了。)

Socket 还可用吗?或者它会被垃圾收集器删除吗?

下一个问题,但实际上是相同的背景。

AsyncTask 完成后,我在 doInBackground 中实例化的类的实例会发生什么? (一旦 doInBackground 和 OnPostExecute 过去了。)

doInBackground(... ) {
IPConnection ipcon = new IPConnection();
}

-------------------------------------------------------- --------------------------------------------------

编辑:

如何创建从 Asynctask 中的对象到 MainActivity 的引用?

编辑2:

这是对主线程的引用吗?该代码示例中的对象不会被垃圾收集器删除吗?

public class ClientActivity extends Activity {


private IPConnection ipcon;

private Socket Testsocket;

public class IPConnection extends AsyncTask<String, String, IPConnection> {

@Override
protected IPConnection doInBackground(String... message) {

ipcon = new IPConnection();


ipcon.run();

return null;
}

}

}

提前谢谢您。

最佳答案

Is the Socket still available? Or will it removed by the Garbage Collector?

否,套接字将不可用,并将被垃圾收集器删除,因为它不包含任何引用

What happens to an instance of a class which I Instantiate in doInBackground after AsyncTask has finished? (As soon as doInBackground and OnPostExecute has passed.)

与上面相同,ipconnection 不持有任何引用,因此它将被垃圾收集器收集

如果您想将其传递给 Activity ,您可以创建一个接口(interface)

public interface AsyncResultPasser {
void passSocket(Socket socket);
void passIPconnection(IPConnection ipcon);
}

然后在你的 asynctask 类中你必须添加

public AsyncResultPasser delegate = null;

并且不要忘记在执行异步任务之前先设置它

public class YourActivity implements AsyncResponse{
YourAsyncTask asyncTask = new YourAsyncTask ();
@Override
public void onCreate(Bundle savedInstanceState) {
asyncTask.delegate = this;
}


void passSocket(Socket socket){
//you can get your socket here
}

void passIPconnection(IPConnection ipcon){
//you can get your ipconnection here
}
}

并且只需使用 delegate.passSocket(socket)delegate.passIPconnection(ipcon)

即可调用它

希望我的回答可以帮助到你:)

关于java - Android 异步任务和 TCP/IP 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18042048/

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