Kkk.
Kkk.

Reputation: 1

Java Android socket gets killed imidiatelly after screen goes blank

I use to connect with server a socket :

Socket requestSocket.connect(new InetSocketAddress(a, 6666), 3000);

It works pretty well all the time except when device stays in idle mode for longer time say 30 mins or so. After 30 mins if I bring device to wake state, and try to contact to server thro' my app it doesn't throw any exception. Which shows me that my socket connection is in still live state. But when I check at the server end same data is not received here.

Upvotes: 1

Views: 327

Answers (1)

Rajesh N
Rajesh N

Reputation: 6693

Battery way is use background service with startForground

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

    onHandleIntent(intent);
    return START_STICKY;
}


protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        Notification.Builder builder = new Notification.Builder(getBaseContext())
                .setContentTitle("")
                .setContentText("Your content text");
        startForeground(1, builder.build());
        Socket requestSocket.connect(new InetSocketAddress(a, 6666), 3000);
    }

}

This service will never pause/closed your socket connection even your app is closed or removed from the recent app.

You can use Bind service from UI if you want to update UI from background service

@Override
    public IBinder onBind(Intent intent) {
        if (TweetCollectorService.class.getName().equals(intent.getAction())) {
            Log.d(TAG, "Bound by intent " + intent);
            return apiEndpoint;
        } else {
            return null;
        }
    }

Upvotes: 1

Related Questions