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 context
variable. 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