lee du
lee du

Reputation: 69

Android Web socket Service is not maintain web connection when mobile screen off

I am using node.js web server by heroku and android client for web socket.io communication

I want to receive server message whenever it send to client Android, even the Android screen off

so I am basically make Service , socket.on listener , thread & handler on Android.

also did apply partial_wake_lock, foreground service, send Notification, ping-pong per every 5 seconds ...

my system is running well when Android's screen is on.

but around 30 seconds after Android screen off, web connection is going to disconnect

could you give me some example about long-run web socket Service source code or some solution about my code?

thank you for read.


mainActivity

 PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK  |
                PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.ON_AFTER_RELEASE, "My:Tag");

        wakeLock.acquire();

//apply wake_lock etc

                  (...)

 Intent serviceIntent = new Intent(getApplicationContext(),CommunicationService.class);
                    startService(serviceIntent); //init service

communication Service (extends Service)

 @Override
    public int onStartCommand(Intent intent, int flags, int startId){

 //start foreground-service

         Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Log.d("gd","entering");
            notification =
                    new Notification.Builder(this, CHANNEL_ID)
                            .setContentTitle("KD SERVICE TEST")
                            .setContentText("now koda testing" )
                            .setSmallIcon(R.drawable.ic_android_ex)
                            .setContentIntent(pendingIntent)
                            .build();


        startForeground(1, notification);


         if(webThread == null) {
            Log.d("gd","webthread begin");
            webThread = new WebThread(url, role, this.handler);
            webThread.start();

        }
        return START_NOT_STICKY; //I tried STICKY, but nothing 


class webThread extend Thread : constructor and run

in the webThread.run, the thread is always send 'ping' to server every 5second and when server get 'ping' always answer 'pong'

in my intention, when there is no 'pong', it means correspond = false, try to socket.connect() again. and this handler is come from communicationService.

 public  WebThread(String get_url, int input_role, android.os.Handler handler){

        try {
            socket = IO.socket(get_url);

            Log.d("gd","socket status: 0  " + socket.connected());

            socket.connect();
            socket.emit("join",role,"01");
        } catch (URISyntaxException e) {
            Log.d("gd", "web server enter failed");
            e.printStackTrace();
        }

        web_listener_init();
        this.handler = handler;
        Log.d("gd","web thread created");

    }



    @Override
    public void run(){

        while(true){
            if(isInterrupted())
                return; 
             //when connection status is fine, correspond == true.
                if(correspond ==false) {
                            socket.connect();
                    socket.emit("join", role, "01");
                }

            Message msg = Message.obtain();
            msg.what = STATE_HEARTBEAT;
            handler.sendMessage(msg);
            correspond = false;

                try {
                    Thread.sleep(5000);
                }
                catch (InterruptedException e){
                    e.printStackTrace();
                }
        }

    }

this is handler in communication service class.

 Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {


                    case STATE_HEARTBEAT:
                        webThread.getSocket().emit("send_ping");
                        //sendNotification("ping");
                        break;

                    case STATE_WEB_MESSAGE_RECEIVED:

                        String webMessage = msg.obj.toString();
                        Log.d("gd", "handler received from web: " + webMessage);

                        if(webMessage.equals("pong")){
                            webThread.isCorrespond(); // make webThread 's 'correspond' = true
                        }
               });


I am using nkzawa Socket.io library. It will be very appreciate for give some advice.

Upvotes: 2

Views: 617

Answers (1)

lee du
lee du

Reputation: 69

I solved my problem. sudden disconnection is not from server / service / ping-pong.

is from android itself.

If don't apply wake_lock(paritial_wake_lock) on SERVICE class,

service do not maintain even its service is foreground, or notify regularly

I did put wake lock only in mainActivity, which is running before the service.

so apply wake_lock on the service and put manifest !

Upvotes: 0

Related Questions