5

I have been working on making USB connection specified in the link here and successfully implemented it. Its working fine accept it is frequently getting disconnected. I got to know from this link and this link that there is a bug in android OS that there is no broadcast event of USB connection event. I have implemented a receiver for getting USB disconnecting event which is not too much important. Also I refer this link to create stable connection with USB i.e. start data communication after USB connection without any loss. This whole thing is working fine when there is single activity or single screen in application.

For multiple screen this connection thing is having problem i.e. connection is not stable and I have multiple screen in application in which I can receive data via USB in any activity at any time. So I have 2 question which I am seeking answers of with some code if possible

  1. How can I make stable connection with device attached via serial USB in android over multiple screens
  2. How to get rid of this frequent disconnection problem in the application over multiple screens

Any help would be greatful

EDIT:

I am adding my service which is responsible for communication with usb and starts a thread for continuous receiving data

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.os.IBinder;
import arya.omnitalk.com.usb.R;
import arya.omnitalk.com.usb.constants.FileReadingWritingConstants;
import arya.omnitalk.com.usb.constants.GeneralConstant;
import arya.omnitalk.com.usb.constants.UsbDataWriterConstants;

import com.hoho.android.usbserial.driver.UsbSerialProber;

public class UsbCommunicationService extends Service{

    public static ArrayList<String> _dataArray = new ArrayList<String>();
    private Thread mCommunicationThread = null;

    private class ReadThread implements Runnable {
        @Override
        public void run() {

            while (mCommunicationThread!= null && !mCommunicationThread.isInterrupted()) {

                // Here I write code to parse data received via USB

                 }          
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); // Creating object of usb manager
        UsbDataWriterConstants.driver = UsbSerialProber.acquire(manager); // Acquiring usb channel

        if (UsbDataWriterConstants.driver != null) {
            try {
                UsbDataWriterConstants.driver.open();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            try {
                ReadThread mReadThread = new ReadThread();
                mCommunicationThread = new Thread(mReadThread);
                mCommunicationThread.start();
            } catch (SecurityException e) {
                DisplayError(R.string.error_security);
                DisplayError(R.string.error_security);
            }
        }

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (mCommunicationThread != null)
            mCommunicationThread.interrupt();
        super.onDestroy();
    }


}
4

2 回答 2

0

您可能会断开连接,因为您的服务只是绑定服务。第一个活动启动,绑定到服务,然后将启动。当您切换到另一个活动时,第一个活动会停止,因此它会解除绑定。此时,服务不再绑定,因此被杀死。绑定服务在这里解释:http: //developer.android.com/guide/components/bound-services.html

只要连接了 USB,您可能需要保持服务运行。为此,您需要一个“持久”服务,一个已启动的服务,如下所述:http: //developer.android.com/guide/components/services.html 您可以在收到的活动的 onCreate 中启动您的服务CONNECTED 事件,使用:

public class HomeActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ...
        Intent intent = new Intent(this, UsbCommunicationService.class);
        startService(intent);
        // ...
    }
}

UsbCommunicationService 将通过此方法启动(不推荐使用 onStart()):

public class UsbCommunicationService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // TODO : connect to USB...

        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.       
        return START_STICKY;
    }
}

接下来,您的所有活动都可以“绑定”、“取消绑定”和“重新绑定”到这个将继续存在的服务。不要忘记在 DISCONNECT 事件上停止它,使用:

stopSelf(); // Will actually stop AFTER all clients unbind... 
于 2013-04-08T23:51:30.780 回答
0

这是我为我的 USB 配件注册的活动代码。

    public class UsbAccessoryAttachedWorkaroundActivity extends Activity {

    /**
     * Used only to catch the USB_ACCESSORY_ATTACHED event, has it is not broadcasted to 
     * anything else than the activity with the right accessory_filter (no Service, nor Receiver...)
     * DETACHED event is broadcasted as other events. 
     */

     @Override
     public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             Intent intent = new Intent(this, UsbService.class);
             startService(intent);
             finish(); // <- die ASAP, without displaying anything.
     }
    }

通过这种方式,您可以获得所有 CONNECT 事件,因为 Activity 不存在 => 每次发现附件时,Android 都会重新启动它...我的服务仅在没有人绑定到它时才启动我的 HomeActivity。如果有人被绑定,则意味着 UI 已经存在,因此我只是通知我的听众 USB 连接已恢复...

于 2013-04-09T09:22:45.010 回答