[英]Android Thread and class behavior question
我正在研究的项目需要这种行为。 将向用户显示一个UI,使用户可以选择连接和断开与服务器的连接。 我还希望此UI显示连接状态,“已连接或已断开连接”。 每当用户单击connect时,应用程序将启动一个处理与服务器连接的线程。 用户仍将查看主UI。 当他们启动该连接并且连接仍然存在时,我希望连接的状态为“已连接”。 如果连接在任何时候都被打破,我希望它显示断开连接。 下面列出的是我到目前为止所拥有的。
我的问题是......我在做线程吗? 这样手机在连接时不会被服务器连接压扁吗?
另外,如何让主UI反映服务器的连接状态并在连接断开时显示?
提前致谢! 如果您还有其他问题,请告诉我。
The server connection thread.
public class ConnectDevice implements Runnable {
private boolean connected;
private ObjectInputStream ois;
public void run() {
try {
InetAddress host = InetAddress.getByName("192.168.234.1");
Socket socket = new Socket(host.getHostName(), 7777);
connected = true;
while (connected) {
try {
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
}
catch (Exception e) {
e.printStackTrace();
}
}
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
connected = false;
} catch (IOException e) {
e.printStackTrace();
connected = false;
} /*catch (ClassNotFoundException e) {
e.printStackTrace();
connected = false;
}*/
}
}
The main UI and main class.
public class SmartApp extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
final Button firstTimeButton = (Button) findViewById(R.id.firstTimeButton);
firstTimeButton.setOnClickListener(
new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent userCreationIntent = new Intent(v.getContext(), UserCreation.class);
startActivityForResult(userCreationIntent, 0);
}
});
final Button connectDeviceButton = (Button) findViewById(R.id.connectDeviceButton);
connectDeviceButton.setOnClickListener(
new View.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent connectDeviceIntent = new Intent(v.getContext(), ConnectDevice.class);
//startActivityForResult(connectDeviceIntent, 0);
Thread cThread = new Thread(new ConnectDevice());
cThread.start();
}
});
}
}
查看AsyncTask ,它是针对此类事情量身定制的。
Android有一个UI线程,这是唯一允许更新UI元素的线程。
您需要有一个后台线程来完成工作,并在完成后回发到UI线程。 AsyncTask是一个Android类,旨在实现这一目标。
一旦您的工作线程结束其工作,并将更新findViewById所采用的UI元素,它将自动在屏幕上更改,而您无需执行任何其他操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.