【问题】
折腾:
期间,遇到的问题是:
线程只运行了一次,没有重复运行。。
【解决过程】
1.参考:
去加一下对应的权限:@Override
public void run() {
// Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
看看是否有效果。。。
还是只运行一次。
2.参考:
才明白:
run,就是task的主要的运行的函数:
所以,如果你不写while(1),while(true)之类的代码,
那当然只会执行一次了。。。。
3.所以去改为:@Override
public void run() {
// Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
//0x0403 / 0x6001: FTDI FT232R UART
final int ft232rUartVid = 0x0403; //1027
final int ft232rUartPid = 0x6001; //24577
boolean bNotFoundUsb = true;
while(bNotFoundUsb)
{
//Toast.makeText(getApplicationContext(), "Begin check usb action", 1000).show();
gLogger.debug("Begin check usb action");
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap deviceList = manager.getDeviceList();
Iterator deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
int usbVid = device.getVendorId();
int usbPid = device.getProductId();
if((usbVid == ft232rUartVid) && (usbPid ==ft232rUartPid) ){
//Toast.makeText(getApplicationContext(), "Found Usb device: FT232R UART", Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "Now send message USB_ACTION_ATTACH to activity ", Toast.LENGTH_LONG).show();
gLogger.debug("Found Usb device: FT232R UART");
gLogger.debug("Now send message USB_ACTION_ATTACH to activit");
Message foundUsbDeviceAttachMsg =new Message();
foundUsbDeviceAttachMsg.what=usb_action.USB_ACTION_ATTACH.getAction();
mHandler.sendMessage(foundUsbDeviceAttachMsg);
bNotFoundUsb = false;
break;
}
else
{
//Toast.makeText(getApplicationContext(), "Found USB VID="+usbVid+" PID=" + usbPid, Toast.LENGTH_LONG).show();
gLogger.debug("Found USB VID="+usbVid+" PID=" + usbPid);
}
}//while(deviceIterator.hasNext()){
try {
int sleepTimeInMs = 200;
gLogger.debug("Sleep milliseconds: " + sleepTimeInMs);
Thread.sleep(sleepTimeInMs);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}//while(bNotFoundUsb)
}//public void run()
然后就可以正常,一直运行了。。。
【总结】
此处的thread的run,就类似于嵌入式系统中的main
如果你不写成死循环:
while(1)
或
while(true)
那么函数执行完了,则线程也就结束了。
当然就只执行一次了。
想要循环执行,则加上对应的
while(1)
或
while(true)
即可。