2016-08-19 70 views
0

我的asyncTask问题。我有我的自定义USB扫描仪。我想用ToggleButton打开和关闭它。扫描工作正常,但asynctask完全阻止用户界面。我什么都不能做。也许你知道我能做些什么才能使它更好用?Android:AsyncTaks阻止我的界面

下面是切换按钮:

mScanLayout.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if(isChecked) 
        task.execute(); 
       if(!isChecked) 
        task.cancel(true); 
      } 
     }); 

这里的AsyncTask:

public class scanAsyncTask extends AsyncTask<Void,Void,Void> { 

     @Override 
     protected Void doInBackground(Void... params) { 
      while(!isCancelled()) { 
       mActivity.runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         adapter = new PartAdapter(getContext(), R.layout.part_item, mParts, mActivity,this); 
         adapter.startScanning(); 
        } 
       }); 
      } 
      return null; 
     } 
    } 

这是从适配器扫描方法:

public void startScanning(){ 
     final PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getContext(), 0, new Intent(ACTION_USB_PERMISSION), 0); 
     IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); 
     getContext().registerReceiver(usbReceiver, filter); 
     UsbManager usbManager = (UsbManager) getContext().getSystemService(Context.USB_SERVICE); 
     HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList(); 
     Iterator<UsbDevice> deviceIterator = deviceList.values().iterator(); 
     UsbDevice device = null; 
     while (deviceIterator.hasNext()) { 
      device = deviceIterator.next(); 
      if (device.getVendorId() == 1659 && device.getProductId() == 8963) { 
       this.device = device; 
       usbManager.requestPermission(device, mPermissionIntent); 
       break; 
      } 
     } 
     final UsbDevice finalDevice = device; 
     final UsbDevice finalDevice1 = device; 
     UsbConnector.CallbackListener listener = new UsbConnector.CallbackListener() { 
      @Override 
      public void onStatusChanged(UsbConnector.Status newStatus) { 
       Toast.makeText(getContext(), "status: " + newStatus, Toast.LENGTH_SHORT).show(); 
      } 

      @Override 
      public void onScanCompleted(String result) { 
       Toast.makeText(getContext(), "result: " + result, Toast.LENGTH_SHORT).show(); 

      } 
     }; 

     UsbConnector connector = new UsbConnector(getContext(), finalDevice1,listener); 
     connector.run(); 

     UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(finalDevice); 
     UsbSerialDevice serial = UsbSerialDevice.createUsbSerialDevice(finalDevice, usbDeviceConnection); 
     serial.open(); 
     serial.setBaudRate(57600); 
     if (finalDevice1 != null) { 
      connector.run(); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      connector.send(pal); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      byte[] received = connector.receive(36); 
      if (received == null) { 
       Toast.makeText(getContext(), "BĹ‚Ä…d inicjalizacji skanera", Toast.LENGTH_SHORT).show(); 
      } 
      if (received != null) { 
       String response = null; 
       long longValue = ByteBuffer.wrap(received).getLong(); 
       response = Long.toHexString(longValue).toUpperCase(); 

       if (response.contains("DAAD0674016F6B26")) { 
        connector.send(readId); 
        try { 
         Thread.sleep(1000); 
        } catch (InterruptedException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
        byte[] receivedTag = connector.receive(36); 
        if (receivedTag != null) { 
         String tag = null; 
         long tagValue = ByteBuffer.wrap(receivedTag).getLong(); 
         tag = Long.toHexString(tagValue).toUpperCase(); 
         if (tag.contentEquals("DAAD046F62ADA900")) { 
          startScanning(); 
          try { 
           Thread.sleep(1000); 
          } catch (InterruptedException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 
         } 
         if (!tag.contains("DAAD046F62ADA900")) { 
          String tag2 = null; 
          long tagValue2 = ByteBuffer.wrap(receivedTag).getLong(); 
          tag2 = Long.toHexString(tagValue2).toUpperCase(); 
          Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
          Ringtone r = RingtoneManager.getRingtone(getContext(), notification); 
          r.play(); 
          int i = 0; 
          for (Part part : mParts) { 
           if(part.getCode().contains(tag2)) { 
            part.setScan(true); 
            part.setScanCounter(part.getScanCounter() + 1); 
            i++; 
            notifyDataSetChanged(); 
           } 
          } 
          if(i==0){ 
           Intent intent = new Intent(getContext(),AddActivity.class); 
           intent.putExtra("tag",tag2); 
           mActivity.startActivityForResult(intent,2); 
          } 
         } 
        } 
       } 
       notifyDataSetChanged(); 
      } 
     } else { 
      Toast.makeText(getContext(), R.string.plug_scanner, Toast.LENGTH_SHORT).show(); 
     } 

    } 

请帮助。

+1

因为即使在AsyncTask中,你的扫描发生在'UI线程'上, – Darpan

回答

1

你doInBackground你这样做:

mActivity.runOnUiThread(new Runnable() { 

这违背了目的,你不上的背景不再执行 - 你是主线程,因此阻止用户界面

+0

当我删除这行时,我得到了Can not在没有调用Looper.prepare()的线程中创建处理程序:/ - Bartos刚刚编辑 – Bartos

+0

是的 - 你需要拆分你可以在UI线程上做的事情以及你不能做的事情 – ligi

+0

所以有没有机会运行在后台扫描?也许不是asynctask,也许是别的? – Bartos

1

这条线你的代码

mActivity.runOnUiThread(new Runnable() { 

在UI线程上运行,你应该在doinbackground返回结果,然后在onPostExecute运行在UI线程中使用它。 doInBackground被设置为不在UI线程上运行,但你迫使它在UI线程上运行

+0

当我删除这一行我已经不能创建处理程序内部线程没有调用Looper.prepare():/ – Bartos

+1

根据AsyncTask doinbackground的@Bartos在后台运行,需要将结果包装到单个对象中,并在onPostexecute中使用该对象,这会自动在UI线程上运行 – androidXP