How To Handle Socket Events As Background Service In Android?
I'm new to Android development and I wanted my app to be able to detect socket events even when app is not active via Background service (so I can do push notification e.g if there
Solution 1:
If you need the socket to be alive even after your application is stopped. Move your socket to the Background service and then you can add the socket events in the service.
Solution 2:
You open socket on main thread. Do not open socket connections on main thread, it will gives you ANR(application not responding) error which is occur due to lots of heavy work on UI thread. It blocks UI thread for more than 5 sec. So I suggest you to open socket connections on thread inside service. Here is example using plain socket:
- Create one service class for starting thread on background service
- Create on Thread class for opening socket connection on thread
create separate class for socket communication
publicclassSocketBackgroundServiceextendsService { privateSocketThread mSocketThread; @Overridepublic IBinder onBind(Intent intent) { returnnull; } @OverridepublicvoidonCreate() { mSocketThread = SocketThread.getInstance(); } @OverridepublicvoidonDestroy() { //stop thread and socket connection here } @Overridepublic int onStartCommand(Intent intent, int flags, int startId) { if (mSocketThread.startThread) { } else { stopSelf(); } returnSTART_STICKY; } } publicclassSocketThreadextendsThread { privatestaticSocketThread mSocketThread; privateSocketClient mSocketClient; privateSocketThread() { } // create single instance of socket thread classpublicstaticSocketThreadgetInstance() { if (mSocketThread == null)//you can use synchronized also { mSocketThread = newSocketThread(); } return mSocketThread; } publicbooleanstartThread() { mSocketClient = newSocketClient(); if (socketClient.isConnected()) { mSocketThread.start() returntrue; } returnfalse; } @Overridepublicvoidrun() { super.run(); while (mSocketClient.isConnected()) { // continue listen } // otherwise remove socketClient instance and stop thread } publicclassSocketClient { //write all code here regarding opening, closing sockets//create constructorpublicSocketClient() { // open socket connection here } publicbooleanisConnected() { returntrue; } }
Post a Comment for "How To Handle Socket Events As Background Service In Android?"