我在android的套接字程序中的run()线程方法中放了几个onclick方法。
他们似乎没有工作。可以将这些onclick监听器放在run()方法中,或者现在可以。不确定为什么按钮在点击它们时没有产生响应。消息未被发送这是我正在使用的两个onclick监听器。一个是sendA,另一个是sendB,他们发送短信testA和testB
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8080);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
final PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
sendA.setOnClickListener(new View.OnClickListener() {
// ananamous inner class override for on click
public void onClick(View v) {
out.println("testA");
}
});
sendB.setOnClickListener(new View.OnClickListener() {
// ananamous inner class override for on click
public void onClick(View v) {
out.println("testB");
}
});
// where you issue the commands
// out.println("testX");
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;
}
}
}
答案 0 :(得分:1)
我做了一个简单的演示,它可以工作;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelpActivity" >
<Button
android:id="@+id/a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A" />
<Button
android:id="@+id/b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/a"
android:text="B" />
</RelativeLayout>
public class HelpActivity extends Activity {
private Button aBtn;
private Button bBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
aBtn = (Button) findViewById(R.id.a);
bBtn = (Button) findViewById(R.id.b);
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
aBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v("a", "a");
}
});
bBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v("b", "b");
}
});
}
}).start();
}
}
当我点击按钮时,LogCat中有日志!
所以,也许你的情况是由序列引起的。我的意思是当你点击按钮时,监听器还没有附加到按钮上。
好吧,如果你坚持在主线程上设置监听器,你可以使用处理程序 This Handler class should be static or leaks might occur: IncomingHandler
答案 1 :(得分:0)
它对我有用
public class sendLogs implements Runnable{
@Override
public void run() {
//your other codes
runOnUiThread(new Runnable() {
@Override
public void run() {
//place your onclick listener method here...
}
}