如何在android中连续将usb串口数据传输到外部设备?

时间:2014-08-17 12:12:55

标签: android serial-port usb data-transfer

我正在设计一个用于usb接口的应用程序,我有一个usb cdc设备,我想用我的android funbook p280进行通信..我以前成功地制作了一个应用程序,用于完成上述使用按钮传输数据..但是现在,当我尝试为持续转移做同样的事情时,我的应用程序崩溃了。我已经尝试使用单独的线程,现在异步,但一切都失败了..我正在使用找到的cdc库 https://github.com/mik3y/usb-serial-for-android

我的代码如下:

package com.example.dds;

import com.hoho.android.usbserial.driver.CdcAcmSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import android.graphics.Typeface;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;


public class DDS extends Activity {


    RelativeLayout astep,fstep,aknob,fknob;
    UsbManager manager;
    ImageView amstep,fqstep,ampknob,freqknob;
    String str= "SET:WAVE:SIN\n";
    Iterator<UsbDevice> deviceIterator;
    UsbDevice dev;
    UsbSerialDriver driver;
    double mPrevAngle=0,mCurrAngle=0;
    TextView freqdisp,ampdisp;
    float x=0,y=0,startAngle=0,stopAngle=250;
    Thread th;
    asyncrun a;
    IntentFilter usbattach,usbdetach;


    //My Broadcast Receiver to detect usb
    BroadcastReceiver usbbr =new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent)
        {
            if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED))
            {
                 //Normal Usb Enumeration

                 manager = (UsbManager) getSystemService(Context.USB_SERVICE);
                    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
                    deviceIterator = deviceList.values().iterator();
                    while(deviceIterator.hasNext())
                    {
                        dev = deviceIterator.next();
                    }
                    if(dev.getProductId()==64905)
                    {
                        Toast t=Toast.makeText(getBaseContext(),"Device Connected",1000);
                        t.show();
                        Object params = 0;
                        a.doInBackground(params);   
            }
                    }
            else if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED))
            {
                dev=null;
                Toast t=Toast.makeText(getBaseContext(),"Device Not Connected",1000);
                t.show();
            }
        }

    };




    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

          //IntentFilters for attach and detach action

            usbattach = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            usbdetach = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
    }

    @Override
    protected void onPause() 
    {
        super.onPause();

        this.unregisterReceiver(usbbr);

    }

    @Override
    protected void onResume() 
    {   
        super.onResume();

       //Registering IntentFilters for Usb attach and detach
        this.registerReceiver(usbbr, usbattach);
        this.registerReceiver(usbbr, usbdetach);
     }

       //My AsyncTask subclass
        public class asyncrun extends AsyncTask{

            @Override
            protected Object doInBackground(Object... params) {

                //Transferring data to usb, These functions below work fine for an OnClick                   
                //but for Continous transfer like async they crash..
                try
                {
                        driver.open();
                        driver.setBaudRate(115200); 
                        byte[] buffer = encodeUTF8(str);
                        byte[] buff = new byte[160];
                        driver.read(buff,100);
                        driver.write(buffer,100);   
                        str = "";
                        while(driver.read(buff,100)> 0)
                        {
                            str = str + decodeUTF8(buff);
                        }
                        ampdisp.setText(""+str);

                    }   catch(IOException e)
                {
                    e.printStackTrace();
                }
                return null;
            }





}   

1 个答案:

答案 0 :(得分:0)

查看AsyncTask的其他示例我认为您不应该通过从Activity调用a.doInBackground()来启动AsyncTask。相反,尝试a.execute();如下所述:http://developer.android.com/reference/android/os/AsyncTask.html