Android Storing Socket.io object for multiple activities -
i making first socket.io based android application. socket sends , receives data web service. there number of screens in application different features. how use same socket connection in these different activities.
i have tried setting , storing socket object in application class , appears work when application goes background , left there time application killed , socket object null causing aoo crash null pointer exception.
public class myapplication extends application { private socket msocket; private final string tag = "application class"; public socket getsocket() { return msocket; } public socket createsocket() { try { manager manager = new manager(new uri("http://0.0.0.0")); } catch (urisyntaxexception urise) { urise.printstacktrace(); } return msocket; } }
access socket in activities
myapplication app; app = (myapplication ) getapplication(); app.getsocket;
you can create singleton manager class socket. allow keep single socket connection accessible entire app. see following code , change according requirement
import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.net.connectivitymanager; import android.net.networkinfo; import android.os.handler; import android.os.looper; import android.os.powermanager; import android.util.log; import com.myapp.app.ui.adapter.onsocketconnectionlistener; import java.util.arraylist; import java.util.list; import io.socket.client.io; import io.socket.client.socket; import io.socket.emitter.emitter; /** * created penguin on 6/30/2016. * <p/> * socketmanager manages socket , internet connection. * provide listeners connection status */ public class socketmanager { /** * constant state_connecting. */ public static final int state_connecting = 1; /** * constant state_connected. */ public static final int state_connected = 2; /** * constant state_disconnected. */ public static final int state_disconnected = 3; /** * constant connecting. */ public static final string connecting = "connecting"; /** * constant connected. */ public static final string connected = "connected"; /** * constant disconnected. */ public static final string disconnected = "disconnected"; private static socketmanager instance; private socketmanager() { } /** * gets instance. * * @return instance */ public synchronized static socketmanager getinstance() { if (instance == null) { instance = new socketmanager(); } return instance; } /** * constant tag. */ public static final string tag = socketmanager.class.getsimplename(); private socket socket; private list<onsocketconnectionlistener> onsocketconnectionlistenerlist; /** * connect socket. * * @param token token * @param userid user id * @param host host * @param port port */ public void connectsocket(string token,string userid, string host, string port) { try { if(socket==null){ string serveraddress = host+":"+port; io.options opts = new io.options(); opts.forcenew = true; opts.reconnection = true; opts.reconnectionattempts=5; opts.secure = true; opts.query = "token=" + token + "&" + "user_id=" + userid; socket = io.socket(serveraddress, opts); socket.on(socket.event_connect, new emitter.listener() { @override public void call(object... args) { firesocketstatus(socketmanager.state_connected); log.i(tag, "socket connected"); } }).on(socket.event_reconnecting, new emitter.listener() { @override public void call(object... args) { log.e(tag, "socket reconnecting"); firesocketstatus(socketmanager.state_connecting); } }).on(socket.event_reconnect_failed, new emitter.listener() { @override public void call(object... args) { log.e(tag, "socket reconnection failed"); // firesocketstatusintent(socketmanager.state_disconnected); } }).on(socket.event_reconnect_error, new emitter.listener() { @override public void call(object... args) { log.e(tag, "socket reconnection error"); // firesocketstatus(socketmanager.state_disconnected); } }).on(socket.event_connect_error, new emitter.listener() { @override public void call(object... args) { log.e(tag, "socket connect error"); firesocketstatus(socketmanager.state_disconnected); socket.disconnect(); } }).on(socket.event_disconnect, new emitter.listener() { @override public void call(object... args) { log.e(tag, "socket disconnect event"); firesocketstatus(socketmanager.state_disconnected); } }).on(socket.event_error, new emitter.listener() { @override public void call(object... args) { try { final string error = (string) args[0]; log.e(tag + " error event_error ", error); if (error.contains("unauthorized") && !socket.connected()) { if (onsocketconnectionlistenerlist != null) { (final onsocketconnectionlistener listener : onsocketconnectionlistenerlist) { new handler(looper.getmainlooper()) .post(new runnable() { @override public void run() { listener.onsocketeventfailed(); } }); } } } } catch (exception e) { log.e(tag, e.getmessage() != null ? e.getmessage() : ""); } } }).on("error", new emitter.listener() { @override public void call(object... args) { log.d(tag, " error"); } }); socket.connect(); }else if(!socket.connected()){ socket.connect(); } } catch (exception e) { e.printstacktrace(); } } private int laststate = -1; /** * fire socket status intent. * * @param socketstate socket state */ public synchronized void firesocketstatus(final int socketstate) { if(onsocketconnectionlistenerlist !=null && laststate!=socketstate){ laststate = socketstate; new handler(looper.getmainlooper()).post(new runnable() { @override public void run() { for(onsocketconnectionlistener listener: onsocketconnectionlistenerlist){ listener.onsocketconnectionstatechange(socketstate); } } }); new handler(looper.getmainlooper()).postdelayed(new runnable() { @override public void run() { laststate=-1; } },1000); } } /** * fire internet status intent. * * @param socketstate socket state */ public synchronized void fireinternetstatusintent(final int socketstate) { new handler(looper.getmainlooper()).post(new runnable() { @override public void run() { if(onsocketconnectionlistenerlist !=null){ for(onsocketconnectionlistener listener: onsocketconnectionlistenerlist){ listener.oninternetconnectionstatechange(socketstate); } } } }); } /** * gets socket. * * @return socket */ public socket getsocket() { return socket; } /** * sets socket. * * @param socket socket */ public void setsocket(socket socket) { this.socket = socket; } /** * destroy. */ public void destroy(){ if (socket != null) { socket.off(); socket.disconnect(); socket.close(); socket=null; } } /** * sets socket connection listener. * * @param onsocketconnectionlistenerlistener on socket connection listener listener */ public void setsocketconnectionlistener(onsocketconnectionlistener onsocketconnectionlistenerlistener) { if(onsocketconnectionlistenerlist ==null){ onsocketconnectionlistenerlist = new arraylist<>(); onsocketconnectionlistenerlist.add(onsocketconnectionlistenerlistener); }else if(!onsocketconnectionlistenerlist.contains(onsocketconnectionlistenerlistener)){ onsocketconnectionlistenerlist.add(onsocketconnectionlistenerlistener); } } /** * remove socket connection listener. * * @param onsocketconnectionlistenerlistener on socket connection listener listener */ public void removesocketconnectionlistener(onsocketconnectionlistener onsocketconnectionlistenerlistener) { if(onsocketconnectionlistenerlist !=null && onsocketconnectionlistenerlist.contains(onsocketconnectionlistenerlistener)){ onsocketconnectionlistenerlist.remove(onsocketconnectionlistenerlistener); } } /** * remove socket connection listener. */ public void removeallsocketconnectionlistener() { if(onsocketconnectionlistenerlist !=null){ onsocketconnectionlistenerlist.clear(); } } /** * type net receiver. */ public static class netreceiver extends broadcastreceiver { /** * tag. */ public final string tag = netreceiver.class.getsimplename(); @override public void onreceive(context context, intent intent) { connectivitymanager cm = (connectivitymanager)context.getsystemservice(context.connectivity_service); networkinfo activenetwork = cm.getactivenetworkinfo(); boolean isconnected = activenetwork != null && activenetwork.isconnectedorconnecting(); socketmanager.getinstance().fireinternetstatusintent( isconnected?socketmanager.state_connected:socketmanager.state_disconnected); if (isconnected) { if(socketmanager.getinstance().getsocket()!=null && !socketmanager.getinstance().getsocket().connected()){ socketmanager.getinstance().firesocketstatus(socketmanager.state_connecting); } powermanager powermanager = (powermanager) context.getsystemservice(context.power_service); boolean isscreenon; if (android.os.build.version.sdk_int >= android.os.build.version_codes.kitkat_watch) { isscreenon = powermanager.isinteractive(); }else{ //noinspection deprecation isscreenon = powermanager.isscreenon(); } if (isscreenon && socketmanager.getinstance().getsocket() !=null) { log.d(tag, "netreceiver: connecting socket"); if(!socketmanager.getinstance().getsocket().connected()){ socketmanager.getinstance().getsocket().connect(); } } }else{ socketmanager.getinstance().firesocketstatus(socketmanager.state_disconnected); if(socketmanager.getinstance().getsocket() !=null){ log.d(tag, "netreceiver: disconnecting socket"); socketmanager.getinstance().getsocket().disconnect(); } } } } }
connecting socket
you can connecting/disconnect socket activity or background service
socketmanager.getinstance().connectsocket(user.gettoken(), user.getuserid(), getresources().getstring(r.string.host), "8000");
update
if in background app killed socket destroy. if want socket remain connected in background have make own logic background service has nothing socket.
Comments
Post a Comment