'Android interface'에 해당되는 글 1건

728x90

Interface 처리에 대한 사항을 정리차원에서 실 사용 예제에서 발췌하여 적어둔다.

3번 객체에 해당하는 부분은 여러 Class 에서 하나의 개발코드에 접근할 수 있도록 인터페이스 상속 처리를 했다.


1. 인터페이스 선언

public interface ISerialListener {
    void onReceive(int msg, int arg0, int arg1, String arg2, Object arg3);
}



2. SerialConnector 코드 발췌

public class SerialConnector {
    private Context mContext;
    private ISerialListener mListener; // 인터페이스 처리
    private Handler mHandler;
    private SerialMonitorThread mSerialThread;

    public SerialConnector(Context context, ISerialListener listener, Handler handler) {
        mContext = context;
        mListener = listener;
        mHandler = handler;
    }

    public void initialize() {
        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(sUsbManager);
        if (availableDrivers.isEmpty()) {
            mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: There is no available device. \n", null);
            return;
        }

        sDriver = availableDrivers.get(0);
        if(sDriver == null) {
            mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Driver is Null \n", null);
            return;
        }

        try {
            sPort.open(mConnection);
            if(BaudRate.isEmpty()){ // 통신 속도 설정값 가져와서 세팅
                sPort.setParameters(9600, 8, 1, 0);  // baudrate:9600, dataBits:8, stopBits:1, parity:N
            } else {
                sPort.setParameters(Integer.parseInt(BaudRate), Integer.parseInt(DataBit), Integer.parseInt(StopBit), Integer.parseInt(Parity));
            }
        } catch (IOException e) {
            mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot open port \n" + e.toString() + "\n", null);
        } finally {
        }

        startThread();
    }

    public void finalize() {
        try {
            sDriver = null;
            stopThread();

            sPort.close();
            sPort = null;
        } catch(Exception ex) {
            mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot finalize serial connector \n" + ex.toString() + "\n", null);
        }
    }

    /*****************************************************
     *    private methods
     ******************************************************/
    // start thread
    private void startThread() {
        mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Start serial monitoring thread \n", null);
        if(mSerialThread == null) {
            mSerialThread = new SerialMonitorThread();
            mSerialThread.start();
        }
    }
    // stop thread
    private void stopThread() {
        if(mSerialThread != null && mSerialThread.isAlive())
            mSerialThread.interrupt();
        if(mSerialThread != null) {
            mSerialThread = null;
        }
    }

    /*****************************************************
     *    Sub classes, Handler, Listener
     ******************************************************/
    public class SerialMonitorThread extends Thread {
        @Override
        public void run() {
            byte readBuffer[] = new byte[4096];

            while(!Thread.interrupted()) {
                if(sPort != null) {
                    Arrays.fill(readBuffer, (byte)0x00);

                    try {
                        // Read and Display to Terminal
                        int numBytesRead = sPort.read(readBuffer, 1000);
                        if(numBytesRead > 0) {

                            // Print message length
                            Message msg = mHandler.obtainMessage(Constants.MSG_READ_DATA_COUNT, numBytesRead, 0, new String(readBuffer));
                            mHandler.sendMessage(msg);

                        } // End of if(numBytesRead > 0)
                    } catch (IOException e) {
                        Message msg = mHandler.obtainMessage(Constants.MSG_SERIAL_ERROR, 0, 0, "Error # run: " + e.toString() + "\n");
                        mHandler.sendMessage(msg);
                    }
                }

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }

            }    // End of while() loop
            finalizeThread();
        }    // End of run()
    }    // End of SerialMonitorThread

}


3. 객체 구현

핵심사항만 발췌하여 유사한 코드 구현시 활용 차원으로 적어둔다.

public class AAA extends AppCompatActivity {
    private static final String TAG = "AAA";
    Context mContext;

    private ActivityHandler mHandler = null;
    private SerialListener mSerialListener = null;
    private SerialConnector mSerialConnector = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tam_ss);
        mContext = AAA.this;
        initView();
    }

    private void initView() {
        connectUsb();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        connectUsb();
    }

    @Override
    protected void onDestroy() {
        releaseUsb();
        super.onDestroy();
    }

    private void connectUsb() {
        searchEndPoint();
        if (usbInterfaceFound != null) {
            setupUsbComm();
        }
    }

    private void releaseUsb() {
        textStatus.setText("releaseUsb()");
        mSerialConnector.finalize();
    }

    private boolean setupUsbComm() {
        boolean success = false;

        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        Boolean permitToRead = manager.hasPermission(deviceFound);

        if (permitToRead) {
            usbDeviceConnection = manager.openDevice(deviceFound);
            if (usbDeviceConnection != null) {
                // Initialize
                mSerialListener = new SerialListener();
                mHandler = new ActivityHandler();

                // Initialize Serial connector and starts Serial monitoring thread.
                mSerialConnector = new SerialConnector(mContext, mSerialListener, mHandler);
                mSerialConnector.initialize();
            }
        } else {
            manager.requestPermission(deviceFound, mPermissionIntent);
            textStatus.setText("Permission: " + permitToRead);
        }
        return success;
    }

    public class SerialListener implements ISerialListener {
        public void onReceive(int msg, int arg0, int arg1, String arg2, Object arg3) {
            switch(msg) {
                case Constants.MSG_DEVICD_INFO:
                    updateReceivedData(arg2);
                    break;
                case Constants.MSG_DEVICE_COUNT:
                    updateReceivedData(Integer.toString(arg0) + " device(s) found \n");
                    break;
                case Constants.MSG_READ_DATA_COUNT:
                    updateReceivedData(Integer.toString(arg0) + " buffer received \n");
                    break;
                case Constants.MSG_READ_DATA:
                    if(arg3 != null) {
                        updateReceivedData((String)arg3);
                    }
                    break;
                case Constants.MSG_SERIAL_ERROR:
                    updateReceivedData(arg2);
                    break;
                case Constants.MSG_FATAL_ERROR_FINISH_APP:
                    finish();
                    break;
            }
        }
    }

    public class ActivityHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case Constants.MSG_DEVICD_INFO:
                    updateReceivedData((String)msg.obj);
                    break;
                case Constants.MSG_DEVICE_COUNT:
                    updateReceivedData(Integer.toString(msg.arg1) + " device(s) found \n");
                    break;
                case Constants.MSG_READ_DATA_COUNT:
                    updateReceivedData(((String)msg.obj));
                    break;
                case Constants.MSG_READ_DATA:
                    if(msg.obj != null) {
                        updateReceivedData((String)msg.obj);
                    }
                    break;
                case Constants.MSG_INPUT_READ:
                    updateReceivedData((String)msg.obj);
                    mDumpTextView.setTextColor(Color.BLUE);
                    break;
                case Constants.MSG_SERIAL_ERROR:
                    updateReceivedData((String)msg.obj);
                    break;
            }
        }
    }
}


'안드로이드 > Interface' 카테고리의 다른 글

Java Interface 예제  (0) 2019.11.18
Android Interface AsyncTask 예제  (0) 2019.11.05
Java Interface Example  (0) 2019.09.05
Java 인터페이스(interface) 개요  (0) 2019.08.20
Android Interface 예제 ★★★  (0) 2018.08.22
블로그 이미지

Link2Me

,