0

I am trying to use ZMQ in an android application. Ideally, I should create the context once and term() it when the app is shutting down.

But unlike the c++ applications. There is no main() function on android. Based on the google document about the activity life cycle. The function onCreate(), onStop() can be called multiple times, the function onDestroy() is only called by system.

Solution1: create/destroy ZMQ context in an asyncTask(). But that would be very expensive.

Solution2: based on the thread Android global variable, I could create a global ZMQ.Context contextvariable. The problem of this method is: there is not proper function to call context.term();.

solution3. Creating a singleton class

import org.zeromq.ZMQ;

public class ZmqHelper {
    private static ZMQ.Context _context;

    public static ZMQ.Context createContext(){
        return getContext();
    }

    public static ZMQ.Context getContext(){
        if(_context == null) {
            _context = ZMQ.context(1);
        }
        return _context;
    }

    private ZmqHelper(){
    }

    public static boolean release(){
        // make sure all sockets are closed
        if(_context != null) {
            _context.term();
            _context = null;
            return true;
        }
        return false;
    }
}

The problem of the singleton is same as solution 2. I have to manually call ZmqHelper.release() //which calls context.term() in some stage. I am not sure where is the good place to invoke the function term() to destroy zmq context.

So what is the correct way to create/terminate a ZMQ context in an android application?

env:

Ubuntu: 16.04 LTS

Android studio: 2.3.3

ZMQ: org.zeromq:jeromq:0.4.0

r0n9
  • 2,505
  • 1
  • 29
  • 43

1 Answers1

1

I think you shall use a singletone instance as more straightforward solution.

All network communication on Android must be held is a separate thread (not UI-thread). So you may term ZMQ.Context when you interrupt the networking thread. If your app doesn't need background network connection (you perform netwroking only at separate Activities) it's better to term ZMQ.Context in onPause() methods of those Activities for performance reasons.

I am using such approach but meet problems with terminating SUB socket. Though I think the approach is pretty well.

f4f
  • 891
  • 5
  • 13