gpt4 book ai didi

java - 使用 AsyncTask 进行 android 网络连接

转载 作者:可可西里 更新时间:2023-11-01 02:33:40 26 4
gpt4 key购买 nike

我在使用 AsyncTask 时遇到了一些问题,因为我以前从未遇到过它,也不知道我在用它做什么。

基本上我正在强制关闭,因为我试图在主类上运行连接。有人可以帮我将 AsyncTask 添加到代码中吗:

package com.smarte.smartipcontrol;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class IPControl extends Activity {

private Socket socket;
private String serverIpAddress;
private static final int REDIRECTED_SERVERPORT = 32;
public PrintWriter out;
public BufferedReader in ;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Get the message from the intent
Intent intent = getIntent();
serverIpAddress = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
createConnection();

}

public void getModel(View view) {
try {
out.println("[m\r\n");
//System.out.print("root\r\n");
while (! in .ready());
String textStatus = readBuffer();

} catch (IOException e) {}
}

public void createConnection() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
readBuffer();
} catch (IOException e) {}


//R.id.textStatus
}

private String readBuffer() throws IOException {
String msg = "";

while ( in .ready()) {
msg = msg + (char) in .read();
}
//System.out.print(msg);
if (msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else return msg;
}

}

最佳答案

通过这个简单的教程,了解什么是 AsyncTask 以及如何使用它:

https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

然后尝试修改您的代码以使用异步任务。如果遇到问题,请返回这里 :-)

关于java - 使用 AsyncTask 进行 android 网络连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13681189/

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