1. Are you ready for the Galaxy S20? Here is everything we know so far!

Passing an object of a Usb Service to another activity

Discussion in 'Android Development' started by Nightpoison, Aug 29, 2019.

  1. Nightpoison

    Nightpoison Newbie
    Thread Starter

    Hello,
    I'm new to Android development and I'm attempting to pass an object of a USB service from one activity to another.

    I've attempted to do it two ways thus far. Implementing Parcelable and Implementing Serializable. Both means cause the system to throw and exception. In regards to Serializable, it threw an IOException.

    Here is the code for my USBService, care of Felhr85.

    Code (Text):
    1. package com.ascenzi.usb_serial_testing;
    2.  
    3. import android.app.PendingIntent;
    4. import android.app.Service;
    5. import android.content.BroadcastReceiver;
    6. import android.content.Context;
    7. import android.content.Intent;
    8. import android.content.IntentFilter;
    9. import android.hardware.usb.UsbDevice;
    10. import android.hardware.usb.UsbDeviceConnection;
    11. import android.hardware.usb.UsbManager;
    12. import android.os.Binder;
    13. import android.os.Handler;
    14. import android.os.IBinder;
    15. import android.util.Log;
    16. import android.widget.TextView;
    17.  
    18. import com.felhr.usbserial.CDCSerialDevice;
    19. import com.felhr.usbserial.UsbSerialDevice;
    20. import com.felhr.usbserial.UsbSerialInterface;
    21.  
    22. import java.io.Serializable;
    23. import java.io.UnsupportedEncodingException;
    24.  
    25. import java.util.HashMap;
    26. import java.util.Map;
    27.  
    28. //import okio.Buffer;
    29.  
    30. public class UsbService extends Service implements Serializable
    31. {
    32.  
    33.     public static final String TAG = "UsbService";
    34.  
    35.     public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
    36.     public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
    37.     public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
    38.     public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
    39.     public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
    40.     public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
    41.     public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
    42.     public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
    43.     public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
    44.     public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
    45.     public static final int MESSAGE_FROM_SERIAL_PORT = 0;
    46.     public static final int CTS_CHANGE = 1;
    47.     public static final int DSR_CHANGE = 2;
    48.     private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    49.     private static final int BAUD_RATE = 115200; // BaudRate. Change this value if you need
    50.     public static boolean SERVICE_CONNECTED = false;
    51.  
    52.     private IBinder binder = new UsbBinder();
    53.  
    54.     private Context context;
    55.     private Handler mHandler;
    56.     private UsbManager usbManager;
    57.     private UsbDevice device;
    58.     private UsbDeviceConnection connection;
    59.     private UsbSerialDevice serialPort;
    60.  
    61.     private TextView t1;
    62.  
    63.     //private Buffer buffer = new Buffer();
    64.     private String mode;
    65.  
    66.     private boolean serialPortConnected;
    67.  
    68.     /*
    69.      *  Data received from serial port will be received here. Just populate onReceivedData with your code
    70.      *  In this particular example. byte stream is converted to String and send to UI thread to
    71.      *  be treated there.
    72.      */
    73.     private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
    74.         @Override
    75.         public void onReceivedData(byte[] arg0) {
    76.             try {
    77.                 String data = new String(arg0, "UTF-8");
    78.                 if (mHandler != null)
    79.                     mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
    80.             } catch (UnsupportedEncodingException e) {
    81.                 e.printStackTrace();
    82.             }
    83.         }
    84.     };
    85.  
    86.     /*
    87.      * State changes in the CTS line will be received here
    88.      */
    89.     private UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {
    90.         @Override
    91.         public void onCTSChanged(boolean state) {
    92.             if(mHandler != null)
    93.                 mHandler.obtainMessage(CTS_CHANGE).sendToTarget();
    94.         }
    95.     };
    96.  
    97.     /*
    98.      * State changes in the DSR line will be received here
    99.      */
    100.     private UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {
    101.         @Override
    102.         public void onDSRChanged(boolean state) {
    103.             if(mHandler != null)
    104.                 mHandler.obtainMessage(DSR_CHANGE).sendToTarget();
    105.         }
    106.     };
    107.     /*
    108.      * Different notifications from OS will be received here (USB attached, detached, permission responses...)
    109.      * About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
    110.      */
    111.     private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
    112.         @Override
    113.         public void onReceive(Context arg0, Intent arg1) {
    114.             if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
    115.                 boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
    116.                 if (granted) // User accepted our USB connection. Try to open the device as a serial port
    117.                 {
    118.                     Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
    119.                     arg0.sendBroadcast(intent);
    120.                     connection = usbManager.openDevice(device);
    121.                     new ConnectionThread().start();
    122.                 } else // User not accepted our USB connection. Send an Intent to the Main Activity
    123.                 {
    124.                     Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
    125.                     arg0.sendBroadcast(intent);
    126.                 }
    127.             } else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
    128.                 if (!serialPortConnected)
    129.                     findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
    130.             } else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
    131.                 // Usb device was disconnected. send an intent to the Main Activity
    132.                 Intent intent = new Intent(ACTION_USB_DISCONNECTED);
    133.                 arg0.sendBroadcast(intent);
    134.                 if (serialPortConnected) {
    135.                     serialPort.close();
    136.                 }
    137.                 serialPortConnected = false;
    138.             }
    139.         }
    140.     };
    141.  
    142.     /*
    143.      * onCreate will be executed when service is started. It configures an IntentFilter to listen for
    144.      * incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
    145.      */
    146.     @Override
    147.     public void onCreate() {
    148.         this.context = this;
    149.         serialPortConnected = false;
    150.         UsbService.SERVICE_CONNECTED = true;
    151.         setFilter();
    152.         usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    153.         findSerialPortDevice();
    154.     }
    155.  
    156.     /* MUST READ about services
    157.      * http://developer.android.com/guide/components/services.html
    158.      * http://developer.android.com/guide/components/bound-services.html
    159.      */
    160.     @Override
    161.     public IBinder onBind(Intent intent) {
    162.         return binder;
    163.     }
    164.  
    165.     @Override
    166.     public int onStartCommand(Intent intent, int flags, int startId) {
    167.         return Service.START_NOT_STICKY;
    168.     }
    169.  
    170.     @Override
    171.     public void onDestroy() {
    172.         super.onDestroy();
    173.         serialPort.close();
    174.         unregisterReceiver(usbReceiver);
    175.         UsbService.SERVICE_CONNECTED = false;
    176.     }
    177.  
    178.     /*
    179.      * This function will be called from MainActivity to write data through Serial Port
    180.      */
    181.     public void write(byte[] data) {
    182.         if (serialPort != null)
    183.         {
    184.             serialPort.write(data);
    185.         }
    186.     }
    187.  
    188.  
    189.     public void setHandler(Handler mHandler) {
    190.         this.mHandler = mHandler;
    191.     }
    192.  
    193.     private void findSerialPortDevice() {
    194.         // This snippet will try to open the first encountered usb device connected, excluding usb root hubs
    195.         HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
    196.         if (!usbDevices.isEmpty()) {
    197.  
    198.             // first, dump the hashmap for diagnostic purposes
    199.             for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
    200.                 device = entry.getValue();
    201.                 Log.d(TAG, String.format("USBDevice.HashMap (vid:pid) (%X:%X)-%b class:%X:%X name:%s",
    202.                                          device.getVendorId(), device.getProductId(),
    203.                                          UsbSerialDevice.isSupported(device),
    204.                                          device.getDeviceClass(), device.getDeviceSubclass(),
    205.                                          device.getDeviceName()));
    206.             }
    207.  
    208.             for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
    209.                 device = entry.getValue();
    210.                 int deviceVID = device.getVendorId();
    211.                 int devicePID = device.getProductId();
    212.  
    213. //                if (deviceVID != 0x1d6b && (devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003) && deviceVID != 0x5c6 && devicePID != 0x904c) {
    214.                 if (UsbSerialDevice.isSupported(device)) {
    215.                     // There is a supported device connected - request permission to access it.
    216.                     requestUserPermission();
    217.                     break;
    218.                 } else {
    219.                     connection = null;
    220.                     device = null;
    221.                 }
    222.             }
    223.             if (device==null) {
    224.                 // There are no USB devices connected (but usb host were listed). Send an intent to MainActivity.
    225.                 Intent intent = new Intent(ACTION_NO_USB);
    226.                 sendBroadcast(intent);
    227.             }
    228.         } else {
    229.             Log.d(TAG, "findSerialPortDevice() usbManager returned empty device list." );
    230.             // There is no USB devices connected. Send an intent to MainActivity
    231.             Intent intent = new Intent(ACTION_NO_USB);
    232.             sendBroadcast(intent);
    233.         }
    234.     }
    235.  
    236.     private void setFilter() {
    237.         IntentFilter filter = new IntentFilter();
    238.         filter.addAction(ACTION_USB_PERMISSION);
    239.         filter.addAction(ACTION_USB_DETACHED);
    240.         filter.addAction(ACTION_USB_ATTACHED);
    241.         registerReceiver(usbReceiver, filter);
    242.     }
    243.  
    244.     /*
    245.      * Request user permission. The response will be received in the BroadcastReceiver
    246.      */
    247.     private void requestUserPermission() {
    248.         Log.d(TAG, String.format("requestUserPermission(%X:%X)", device.getVendorId(), device.getProductId() ) );
    249.         PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    250.         usbManager.requestPermission(device, mPendingIntent);
    251.     }
    252.  
    253.     public class UsbBinder extends Binder {
    254.         public UsbService getService() {
    255.             return UsbService.this;
    256.         }
    257.     }
    258.  
    259.     /*
    260.      * A simple thread to open a serial port.
    261.      * Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
    262.      */
    263.     private class ConnectionThread extends Thread {
    264.         @Override
    265.         public void run() {
    266.             serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
    267.             if (serialPort != null) {
    268.                 if (serialPort.open()) {
    269.                     serialPortConnected = true;
    270.                     serialPort.setBaudRate(BAUD_RATE);
    271.                     serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
    272.                     serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
    273.                     serialPort.setParity(UsbSerialInterface.PARITY_NONE);
    274.                     /**
    275.                      * Current flow control Options:
    276.                      * UsbSerialInterface.FLOW_CONTROL_OFF
    277.                      * UsbSerialInterface.FLOW_CONTROL_RTS_CTS only for CP2102 and FT232
    278.                      * UsbSerialInterface.FLOW_CONTROL_DSR_DTR only for CP2102 and FT232
    279.                      */
    280.                     serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
    281.                     serialPort.read(mCallback);
    282.                     serialPort.getCTS(ctsCallback);
    283.                     serialPort.getDSR(dsrCallback);
    284.  
    285.                     //
    286.                     // Some Arduinos would need some sleep because firmware wait some time to know whether a new sketch is going
    287.                     // to be uploaded or not
    288.                     //Thread.sleep(2000); // sleep some. YMMV with different chips.
    289.  
    290.                     // Everything went as expected. Send an intent to MainActivity
    291.                     Intent intent = new Intent(ACTION_USB_READY);
    292.                     context.sendBroadcast(intent);
    293.                 } else {
    294.                     // Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
    295.                     // Send an Intent to Main Activity
    296.                     if (serialPort instanceof CDCSerialDevice) {
    297.                         Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
    298.                         context.sendBroadcast(intent);
    299.                     } else {
    300.                         Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
    301.                         context.sendBroadcast(intent);
    302.                     }
    303.                 }
    304.             } else {
    305.                 // No driver for given device, even generic CDC driver could not be loaded
    306.                 Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
    307.                 context.sendBroadcast(intent);
    308.             }
    309.         }
    310.     }
    311. }
    312.  
    . When I attempt to pass the Object itself I do the following.

    Code (Text):
    1. private UsbService usbService;
    2. ...
    3. Button swchBtn = (Button) findViewById(R.id.buttonSwitch);
    4.         swchBtn.setOnClickListener(new View.OnClickListener() {
    5.             @Override
    6.             public void onClick (View v)
    7.             {
    8.  
    9.                 if(usbService != null)
    10.                 {
    11.                     Intent swIntent = new Intent(MainActivity.this, SecondActivity.class);
    12.                     swIntent.putExtra("USBService", usbService);
    13.                     startActivity(swIntent);
    14.                 }
    15.             }
    before I switch activities I have done a quick check to make sure that it wasn't equal to "null". I'll change it up later and say if it is equal to null then I'll jump over but I won't send a intent extra. But for now it just crashes every time.

    Any insight?

    Michael
     


Loading...

Share This Page

Loading...