我正在开发基于套接字的android应用程序,其中我需要获取按钮的状态,无论是ON还是OFF。所以我想要的是我只想要运行线程的更新结果意味着如果任何按钮的状态发生变化,那么我应该得到通知我可以相应地设置按钮状态。
这是我的主要课每秒检查一次结果。
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("connected");
try {
s = new Socket("192.168.1.19", 502);
i = s.getInputStream();
iD = new DataInputStream(i);
o = s.getOutputStream();
oD = new DataOutputStream(o);
System.out.println("connected");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}, 0,1000);
}
这里我使用了每秒运行的TimerTask
。但不想使用计时器任务。
这里是 ClientThread.java
public class ClientThread implements Runnable {
PollThread pollThread;
String byte_to_hex,swapped_result,result;
@Override
public void run()
{
// TODO Auto-generated method stub
try
{
byte[] data1 = new byte[1024], packet1 =
{
(byte) 0x00,(byte) 0x00,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x06,
(byte) 0x01,(byte) 0x01,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x19
};
PollThread.o.write(packet1);
PollThread.i.read(data1, 0, 1024);
/*Log.v("::::TX::::", ConversionMethods.bytesToHex(data1).substring(0, 26));
Log.v("::::RX::::", ConversionMethods.bytesToHex(packet1));*/
byte_to_hex = ConversionMethods.bytesToHex(data1).substring(18, 26);
System.out.println(byte_to_hex);
char[] arr = byte_to_hex.toCharArray();
for (int i = 0; i < arr.length - 1; i += 2)
{
char temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
swapped_result=new String(arr);
result = ConversionMethods.hexStringToNBitBinary(swapped_result, 32);
System.out.println(result);
}
catch (UnknownHostException e) {
// TODO: handle exception
System.out.println("In Catch Block");
e.printStackTrace();
}
catch (IOException e) {
// TODO: handle exception
System.out.println("In Catch Block");
e.printStackTrace();
}
}
}
这里任何按钮的状态都会改变,我会得到不同的结果。所以我想要这个更新的状态值。基于此,我可以采取一些行动。
由于
答案 0 :(得分:0)
初始化时将按钮传递给线程。您可以从线程访问状态。
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
Thread cThread = new Thread(new ClientThread(myButton));
cThread.start();
}
}, 0,1000);
public class ClientThread implements Runnable {
PollThread pollThread;
String byte_to_hex,swapped_result,result;
public ClientThread(Button btn){
this.button = btn
}
@Override
public void run()
{
...