最近研究利用Asynctask建立套接字连接,但遇到了一些情况 现在我可以用按钮来建立连接,但我不知道如何使按钮文本从“未连接”变为“已连接”。编译没问题但是无法在模拟器上执行,按下按钮,我可以看到从“未连接”到“已连接”的文本,但下一秒强制关闭APP。
以下是我的代码片段:
public class MainActivity extends Activity {
public static Button Btn_Wifi,Btn_Power,Btn_Flame;
public static Boolean connected=false;
public static DataOutputStream dataOutputStream = null;
public static DataInputStream dataInputStream = null ;
public static Socket socket;
的AsyncTask:
static class SocketTask extends AsyncTask<Void, Void, Void > {
@Override
protected Void doInBackground(Void ... parms) {
try {
socket = new Socket("ip", port);//
dataOutputStream = new DataOutputStream(socket.getOutputStream());//and stream
changeConnectionStatus(true);//change the connection status
}catch (UnknownHostException e) {
}catch (IOException e) {
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
};
Button.OnClickListener:
Button.OnClickListener BtnWifiOnClickListener = new Button.OnClickListener(){
@Override
public void onClick(View view) {
//SocketTask sockettask = new SocketTask();
new SocketTask().execute();
}
};
changeConnectionStatus:
public static void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
if(isConnected){//if connection established
Btn_Wifi.setText("connected");
Btn_Power.setEnabled(true);
}else{
Btn_Wifi.setText("unconnected");
Btn_Power.setText("POWER OFF");
Btn_Power.setEnabled(false);
PowerStatus(false);
}
}
积极的解决方案
@Override
protected void onPostExecute(Void result) {
changeConnectionStatus(true);
}
答案 0 :(得分:1)
您无法触及doInBackground()
您需要使用onPostExecute()
从changeConnectionStatus(true)
()移动doInBackground
的来电,如下所示:
@Override
protected void onPostExecute() {
changeConnectionStatus(true);
}