daily pastebin goal
40%
SHARE
TWEET

Untitled

a guest Dec 13th, 2018 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class MainActivity extends AppCompatActivity {
  2.  
  3. private Boolean statusUSB = false;
  4.  
  5. /*
  6.  * Notifications from UsbService will be received here.
  7.  */
  8. private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
  9.     @Override
  10.     public void onReceive(Context context, Intent intent) {
  11.         switch (intent.getAction()) {
  12.             case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
  13.                 Toast.makeText(context, "USB Listo1233", Toast.LENGTH_SHORT).show();
  14.                 break;
  15.             case UsbService.ACTION_USB_ATTACHED: // ACTION_USB_ATTACHED
  16.                 Toast.makeText( context, "Usb Conectado2!", Toast.LENGTH_SHORT ).show();
  17.                 break;
  18.             case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
  19.                 Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
  20.                 break;
  21.             case UsbService.ACTION_NO_USB: // NO USB CONNECTED
  22.                 Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
  23.                 break;
  24.             case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
  25.                 Toast.makeText(context, "Usb Desonectado2!", Toast.LENGTH_SHORT).show();
  26.                 break;
  27.             case UsbService.ACTION_USB_READY: // USB NOT SUPPORTED
  28.                 Toast.makeText(context, "USB Isto", Toast.LENGTH_SHORT).show();
  29.                 break;
  30.         }
  31.     }
  32. };
  33. private UsbService usbService;
  34. private TextView display1, display2;
  35. private EditText editText1, editText2;
  36. private Button button1, button2;
  37. private MyHandler mHandler;
  38.  
  39. private final ServiceConnection usbConnection = new ServiceConnection() {
  40.     @Override
  41.     public void onServiceConnected(ComponentName arg0, IBinder arg1) {
  42.         usbService = ((UsbService.UsbBinder) arg1).getService();
  43.         usbService.setHandler(mHandler);
  44.     }
  45.  
  46.     @Override
  47.     public void onServiceDisconnected(ComponentName arg0) {
  48.         usbService = null;
  49.     }
  50. };
  51.  
  52. @Override
  53. protected void onCreate(Bundle savedInstanceState) {
  54.     super.onCreate(savedInstanceState);
  55.     setContentView(R.layout.activity_main);
  56.  
  57.     Bundle bundle = getIntent().getExtras();
  58.     statusUSB = bundle.getBoolean("statusUSBX");
  59.  
  60.     display1 = findViewById(R.id.textView1);
  61.     display2 = findViewById(R.id.textView2);
  62.  
  63.     mHandler = new MyHandler(this);
  64. }
  65.  
  66. @Override
  67. public void onResume() {
  68.     super.onResume();
  69.     setFilters();  // Start listening notifications from UsbService
  70.     startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
  71.  
  72.     Bundle bundle = this.getIntent().getExtras();
  73.     if(bundle != null) {
  74.         //statusUSB = bundle.getBoolean( "statusUSBX" );
  75.  
  76.         if (statusUSB == true) {
  77.             Toast.makeText( this, "Usb Conectado!", Toast.LENGTH_SHORT ).show();
  78.         }
  79.         if (statusUSB == false) {
  80.             Toast.makeText( this, "Usb Desconectado!", Toast.LENGTH_SHORT ).show();
  81.         }
  82.     }
  83. }
  84.  
  85. @Override
  86. public void onPause() {
  87.     super.onPause();
  88.     unregisterReceiver(mUsbReceiver);
  89.     unbindService(usbConnection);
  90. }
  91.  
  92. private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
  93.     if (!UsbService.SERVICE_CONNECTED) {
  94.         Intent startService = new Intent(this, service);
  95.         if (extras != null && !extras.isEmpty()) {
  96.             Set<String> keys = extras.keySet();
  97.             for (String key : keys) {
  98.                 String extra = extras.getString(key);
  99.                 startService.putExtra(key, extra);
  100.             }
  101.         }
  102.         startService(startService);
  103.     }
  104.     Intent bindingIntent = new Intent(this, service);
  105.     bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
  106. }
  107.  
  108. private void setFilters() {
  109.     IntentFilter filter = new IntentFilter();
  110.     filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
  111.     filter.addAction(UsbService.ACTION_NO_USB);
  112.     filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
  113.     filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
  114.     filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
  115.     registerReceiver(mUsbReceiver, filter);
  116. }
  117.  
  118. /*
  119.  * This handler will be passed to UsbService. Data received from serial port is displayed through this handler
  120.  */
  121. private static class MyHandler extends Handler {
  122.     private final WeakReference<MainActivity> mActivity;
  123.  
  124.     public MyHandler(MainActivity activity) {
  125.         mActivity = new WeakReference<>(activity);
  126.     }
  127.  
  128.     @Override
  129.     public void handleMessage(Message msg) {
  130.         switch (msg.what) {
  131.             case UsbService.SYNC_READ:
  132.                 String buffer = (String) msg.obj;
  133.                 if(msg.arg1 == 0){
  134.                     mActivity.get().display1.append(buffer);
  135.                 }else if(msg.arg1 == 1){
  136.                     mActivity.get().display2.append(buffer);
  137.                 }
  138.  
  139.                 break;
  140.         }
  141.     }
  142. }
  143. }
  144.    
  145. public class UsbService extends Service implements SerialPortCallback {
  146.  
  147. public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
  148. public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
  149. public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
  150. public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
  151. public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
  152. public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
  153. public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
  154. public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
  155. public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
  156. public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
  157. public static final int MESSAGE_FROM_SERIAL_PORT = 0;
  158. public static final int CTS_CHANGE = 1;
  159. public static final int DSR_CHANGE = 2;
  160. public static final int SYNC_READ = 3;
  161. private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
  162. private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
  163. public static boolean SERVICE_CONNECTED = false;
  164.  
  165. private List<UsbSerialDevice> serialPorts;
  166.  
  167. private Context context;
  168. private UsbManager usbManager;
  169. private SerialPortBuilder builder;
  170.  
  171. private Handler writeHandler;
  172. private WriteThread writeThread;
  173.  
  174. private ReadThreadCOM readThreadCOM1, readThreadCOM2;
  175.  
  176. private IBinder binder = new UsbBinder();
  177.  
  178. private Handler mHandler;
  179.  
  180. private Boolean statusUSB = false;
  181.  
  182. /*
  183.  * Different notifications from OS will be received here (USB attached, detached, permission responses...)
  184.  * About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
  185.  */
  186. private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
  187.     @Override
  188.     public void onReceive(Context arg0, Intent arg1) {
  189.         if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
  190.             boolean ret = builder.openSerialPorts( context, BAUD_RATE,
  191.                     UsbSerialInterface.DATA_BITS_8,
  192.                     UsbSerialInterface.STOP_BITS_1,
  193.                     UsbSerialInterface.PARITY_NONE,
  194.                     UsbSerialInterface.FLOW_CONTROL_OFF );
  195.             if (ret){
  196.                 Toast.makeText( context, "Usb Conectado1!", Toast.LENGTH_SHORT ).show();
  197.  
  198.                 statusUSB = true;
  199.                 Intent intent2 = new Intent(context, MainActivity.class );
  200.                 intent2.putExtra( "statusUSBX", true );
  201.                 startActivity(intent2);
  202.             }
  203.  
  204.         } else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
  205.  
  206.             UsbDevice usbDevice = arg1.getParcelableExtra(UsbManager.EXTRA_DEVICE);
  207.             boolean ret = builder.disconnectDevice(usbDevice);
  208.             Toast.makeText(context, "Usb Desonectado1!", Toast.LENGTH_SHORT).show();
  209.  
  210.             Intent intent = new Intent(ACTION_USB_DISCONNECTED);
  211.             arg0.sendBroadcast(intent);
  212.  
  213.             statusUSB = false;
  214.             Intent intent2 = new Intent(context, MainActivity.class );
  215.             intent2.putExtra( "statusUSBX", false );
  216.             startActivity(intent2);
  217.         }
  218.     }
  219. };
  220.  
  221. @Override
  222. public void onSerialPortsDetected(List<UsbSerialDevice> serialPorts) {
  223.     this.serialPorts = serialPorts;
  224.  
  225.     if(serialPorts.size() == 0)
  226.         return;
  227.  
  228.     if (writeThread == null) {
  229.         writeThread = new WriteThread();
  230.         writeThread.start();
  231.     }
  232.  
  233.     int index = 0;
  234.  
  235.     if (readThreadCOM1 == null && index <= serialPorts.size()-1
  236.             && serialPorts.get(index).isOpen()) {
  237.         readThreadCOM1 = new ReadThreadCOM(index,
  238.                 serialPorts.get(index).getInputStream());
  239.         readThreadCOM1.start();
  240.     }
  241.  
  242.     index++;
  243.     if(readThreadCOM2 == null && index <= serialPorts.size()-1
  244.             && serialPorts.get(index).isOpen()){
  245.         readThreadCOM2 = new ReadThreadCOM(index,
  246.                 serialPorts.get(index).getInputStream());
  247.         readThreadCOM2.start();
  248.     }
  249. }
  250.  
  251. @Override
  252. public void onCreate() {
  253.     this.context = this;
  254.     UsbService.SERVICE_CONNECTED = true;
  255.     setFilter();
  256.     usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
  257.     builder = SerialPortBuilder.createSerialPortBuilder(this);
  258.  
  259.     boolean ret = builder.openSerialPorts(context, BAUD_RATE,
  260.             UsbSerialInterface.DATA_BITS_8,
  261.             UsbSerialInterface.STOP_BITS_1,
  262.             UsbSerialInterface.PARITY_NONE,
  263.             UsbSerialInterface.FLOW_CONTROL_OFF);
  264.  
  265.     if(!ret) {
  266.         Toast.makeText( context, "No Usb serial ports available", Toast.LENGTH_SHORT ).show();
  267.         UsbService.SERVICE_CONNECTED = false;
  268.     }
  269. }
  270.  
  271. @Nullable
  272. @Override
  273. public IBinder onBind(Intent intent) {
  274.     return binder;
  275. }
  276.  
  277. @Override
  278. public int onStartCommand(Intent intent, int flags, int startId) {
  279.     return Service.START_NOT_STICKY;
  280. }
  281.  
  282. @Override
  283. public void onDestroy() {
  284.     super.onDestroy();
  285.     if(builder != null)
  286.         builder.unregisterListeners(context);
  287.     UsbService.SERVICE_CONNECTED = false;
  288. }
  289.  
  290. public void write(byte[] data, int port){
  291.     if(writeThread != null)
  292.         writeHandler.obtainMessage(0, port, 0, data).sendToTarget();
  293. }
  294.  
  295. public void setHandler(Handler mHandler) {
  296.     this.mHandler = mHandler;
  297. }
  298.  
  299.  
  300. private void setFilter() {
  301.     IntentFilter filter = new IntentFilter();
  302.     filter.addAction(ACTION_USB_PERMISSION);
  303.     filter.addAction(ACTION_USB_DETACHED);
  304.     filter.addAction(ACTION_USB_ATTACHED);
  305.     registerReceiver(usbReceiver, filter);
  306. }
  307.  
  308. public class UsbBinder extends Binder {
  309.     public UsbService getService() {
  310.         return UsbService.this;
  311.     }
  312. }
  313.  
  314. private class ReadThreadCOM extends Thread {
  315.     private int port;
  316.     private AtomicBoolean keep = new AtomicBoolean(true);
  317.     private SerialInputStream inputStream;
  318.  
  319.     public ReadThreadCOM(int port, SerialInputStream serialInputStream){
  320.         this.port = port;
  321.         this.inputStream = serialInputStream;
  322.     }
  323.  
  324.     @Override
  325.     public void run() {
  326.         while(keep.get()){
  327.             if(inputStream == null)
  328.                 return;
  329.             int value = inputStream.read();
  330.             if(value != -1) {
  331.                 String str = toASCII(value);
  332.                 mHandler.obtainMessage(SYNC_READ, port, 0, str).sendToTarget();
  333.             }
  334.         }
  335.     }
  336.  
  337.     public void setKeep(boolean keep){
  338.         this.keep.set(keep);
  339.     }
  340. }
  341.  
  342. private static String toASCII(int value) {
  343.     int length = 4;
  344.     StringBuilder builder = new StringBuilder(length);
  345.     for (int i = length - 1; i >= 0; i--) {
  346.         builder.append((char) ((value >> (8 * i)) & 0xFF));
  347.     }
  348.     return builder.toString();
  349. }
  350.  
  351. private class WriteThread extends Thread{
  352.  
  353.     @Override
  354.     @SuppressLint("HandlerLeak")
  355.     public void run() {
  356.         Looper.prepare();
  357.         writeHandler = new Handler(){
  358.             @Override
  359.             public void handleMessage(Message msg) {
  360.                 int port = msg.arg1;
  361.                 byte[] data = (byte[]) msg.obj;
  362.                 if(port <= serialPorts.size()-1) {
  363.                     UsbSerialDevice serialDevice = serialPorts.get(port);
  364.                     serialDevice.getOutputStream().write(data);
  365.                 }
  366.             }
  367.         };
  368.         Looper.loop();
  369.     }
  370. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top