Search code examples
javaandroidmultithreadingandroid-activityuart

Android application optimal design with several activities


I'm developing a quite big app with several activities, see link, and I have 2 questions about the base design.

  1. What is best practise concerning opening activities, so that that i don't waste memory by having multiple instances of the same class open at same time and such?

  2. The app must receive USB-data constantly through a UART-interface, and should somehow forward this data to the activity in focus. For now the start activity receive the data through a handler. this would work if only one activity needed the USB-data. How should I do this?

Start.java

final Handler handler = new Handler()
{
    @Override 
    public void handleMessage(Message msg)
    {
        if(actualNumBytes[0] != 0x00)
        {
            info.append(String.copyValueOf(readBuffer, 0, actualNumBytes[0]));
        }
    }
};

handler_thread.java

/*usb input data handler*/
private class handler_thread extends Thread 
{
    Handler mHandler;

    handler_thread(Handler h ){
        mHandler = h;
    }

    public void run()
    {
        while(true)
        {
            Message msg = mHandler.obtainMessage();
            try{
                Thread.sleep(50);
            } 
            catch(InterruptedException e){}

            status = uartInterface.ReadData((byte)64, readBuffer, actualNumBytes);
            mHandler.sendMessage(msg);
        }
    }
}

Solution

    1. If you wish to minimize the number of activities, consider using fragments instead.

    2. If you have a global variable/event/thread that need to be handled by the current activity, put it in a service, and let the activity communicate with it (connect on start/resume, disconnect on pause/stop).

    Hope this helps.