嗨,我是编程新手。我正在使用 onClick(View v) 启动一个线程。它工作正常。现在我想重复“按钮单击”而不再次单击按钮。我正在寻找大约5个小时。但我没有得到任何答案。我用户 button.performClick(); 但什么也没发生。我想重新启动我的线程。
接收者:
private OnClickListener connectListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setPressed(false);
connectPhones.invalidate();
Handler handler1 = new Handler();
Runnable r1 = new Runnable() {
public void run() {
connectPhones.performClick();
connectPhones.setPressed(true);
connectPhones.invalidate();
connectPhones.setPressed(false);
connectPhones.invalidate();
}
};
handler1.postDelayed(r1, 1000);
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
final String path = "/sdcard/all.png";
File file = new File(path);
ObjectInputStream reader = new ObjectInputStream(socket.getInputStream());
int nRead = 0;
byte[] data = new byte[socket.getReceiveBufferSize()];
FileOutputStream fileOutputStream = new FileOutputStream( path );
// while(connected == true){
while( (nRead = reader.read(data)) != -1 ){
fileOutputStream.write( data, 0, nRead );
fileOutputStream.flush();
data = new byte[socket.getReceiveBufferSize()];
}
fileOutputStream.close();
//}
handler.post(new Runnable() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeFile(path);
image.setImageBitmap(bitmap);
image.postInvalidate();
}
});
file.delete();
reader.close();
//connectPhones.performClick();
/* while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}*/
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
}
connected = false;
}
}
}