线程中设置UI问题:
Android处于安全考虑,禁止在子线程中队系统的UI进行操作,因此,需要通过Handler对其进行处理。
在子线程中,当需要进行UI相关操作时,可通过Handler类实现。
1.在主线程中创建Handler,其功能为监听msg,当收到msg时进行一些操作
public Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) {...}}}2.在子线程中发送msg:
new Thread(new Runnable() { public void run() { try { mHandler.obtainMessage(1).sendToTarget(); Thread.sleep(1000); <span style="white-space:pre"> </span>} } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start();
本例中为长按某按钮时,手机通过TCP持续发送某个命令
public void hookMove(final Activity activity, final String cmd, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { Toast.makeText(activity, "钩子开始移动", Toast.LENGTH_SHORT).show(); longClicked = true; Thread t = new Thread() { @Override public void run() { super.run(); while (longClicked) { // 发送命令 TCPControl.sendCMD(cmd); try { Thread.sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.start(); } else if (event.getAction() == MotionEvent.ACTION_UP) { Toast.makeText(activity, "钩子停止移动", Toast.LENGTH_SHORT).show(); longClicked = false; System.out.println("ACTION_UP"); } }
hookUp.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub cmd = "12" + strHookSelected + "3"; hookMove(activity, cmd, event); return true; } });
相对于系统提供的isConnected等函数来说,通过模拟Linux中的ping操作效果更好(http://blog.csdn.net/yudajun/article/details/10062339)
代码功能为向指定ip发送一个ping命令,若成功,则证明socket为连接状态
private static boolean startPing(String ip) { boolean success = false; Process p = null; try { p = Runtime.getRuntime().exec("ping -c 1 -i 0.2 -W 1 " + ip); int status = p.waitFor(); if (status == 0) { success = true; } else { success = false; } } catch (Exception e) { success = false; } finally { p.destroy(); } return success; }
Android线程中队UI进行操作、按钮长按实现连续发送命令的效果、检测socket与服务器连接状态
原文地址:http://blog.csdn.net/miaoyunzexiaobao/article/details/41478033