Skip to content

Commit 995fe0a

Browse files
committed
fix reconnection
1 parent ed4b6ec commit 995fe0a

File tree

8 files changed

+154
-140
lines changed

8 files changed

+154
-140
lines changed

library/src/main/java/com/getstream/sdk/chat/function/MessageFunction.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.getstream.sdk.chat.function;
22

3+
import android.content.Context;
34
import android.support.annotation.NonNull;
45
import android.support.annotation.Nullable;
56

@@ -10,6 +11,7 @@
1011
import com.getstream.sdk.chat.rest.apimodel.request.UpdateMessageRequest;
1112
import com.getstream.sdk.chat.rest.apimodel.response.ChannelResponse;
1213
import com.getstream.sdk.chat.rest.apimodel.response.MessageResponse;
14+
import com.getstream.sdk.chat.utils.Constant;
1315
import com.getstream.sdk.chat.utils.Global;
1416

1517
import java.util.List;
@@ -19,17 +21,18 @@ public class MessageFunction {
1921
private final String TAG = MessageFunction.class.getSimpleName();
2022

2123
private ChannelResponse channelResponse;
24+
private Context context;
2225

23-
public MessageFunction(ChannelResponse channelResponse) {
26+
public MessageFunction(ChannelResponse channelResponse, Context context) {
2427
this.channelResponse = channelResponse;
28+
this.context = context;
2529
}
2630

2731
// region Message
2832
public void sendMessage(@Nullable String text,
2933
@Nullable List<Attachment> attachments,
3034
@Nullable String parentId,
3135
final MessageSendListener sendListener) {
32-
3336
List<String> mentionedUserIDs = channelResponse.getMentionedUserIDs(text);
3437
SendMessageRequest request = new SendMessageRequest(text, attachments, parentId, false, mentionedUserIDs);
3538
Global.mRestController.sendMessage(channelResponse.getChannel().getId(), request,

library/src/main/java/com/getstream/sdk/chat/rest/WebSocketService.java

Lines changed: 59 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
package com.getstream.sdk.chat.rest;
22

3+
import android.app.Activity;
4+
import android.content.BroadcastReceiver;
5+
import android.content.Context;
6+
import android.content.Intent;
7+
import android.content.IntentFilter;
38
import android.os.Handler;
49
import android.text.TextUtils;
510
import android.util.Log;
611

712
import com.getstream.sdk.chat.interfaces.WSResponseHandler;
813
import com.getstream.sdk.chat.model.Event;
14+
import com.getstream.sdk.chat.utils.ConnectionChecker;
915
import com.getstream.sdk.chat.utils.Constant;
1016
import com.getstream.sdk.chat.utils.Global;
17+
import com.getstream.sdk.chat.utils.Utils;
1118

1219
import org.json.JSONException;
1320
import org.json.JSONObject;
@@ -32,21 +39,57 @@ public class WebSocketService extends WebSocketListener {
3239
private Request request;
3340
private EchoWebSocketListener listener;
3441
private WebSocket webSocket;
42+
private Context context;
3543

36-
public void setWSResponseHandler(WSResponseHandler responseHandler) {
37-
if (webSocketListeners == null) webSocketListeners = new ArrayList<>();
38-
if (!webSocketListeners.contains(responseHandler)) {
39-
webSocketListeners.add(responseHandler);
44+
public void setWSResponseHandler(WSResponseHandler responseHandler, Context context) {
45+
if (this.context == null) this.context = context;
46+
if (this.webSocketListeners == null) this.webSocketListeners = new ArrayList<>();
47+
if (!this.webSocketListeners.contains(responseHandler)) {
48+
this.webSocketListeners.add(responseHandler);
4049
}
50+
setBroadCast();
51+
ConnectionChecker.startConnectionCheck(this.context);
4152
}
4253

4354
public void removeWSResponseHandler(WSResponseHandler responseHandler) {
44-
if (webSocketListeners == null || webSocketListeners.isEmpty()) return;
45-
if (webSocketListeners.contains(responseHandler)) {
46-
webSocketListeners.remove(responseHandler);
55+
if (this.webSocketListeners == null || this.webSocketListeners.isEmpty()) return;
56+
if (this.webSocketListeners.contains(responseHandler)) {
57+
this.webSocketListeners.remove(responseHandler);
4758
}
4859
}
4960

61+
private void setBroadCast(){
62+
if (filter != null) return;
63+
64+
filter = new IntentFilter();
65+
filter.addAction(Constant.BC_CONNECTION_OFF);
66+
filter.addAction(Constant.BC_CONNECTION_ON);
67+
filter.addCategory(Intent.CATEGORY_DEFAULT);
68+
this.context.registerReceiver(receiver, filter);
69+
}
70+
IntentFilter filter;
71+
private BroadcastReceiver receiver = new BroadcastReceiver() {
72+
@Override
73+
public void onReceive(Context context, Intent intent) {
74+
// Check Ephemeral Messages
75+
switch (intent.getAction()) {
76+
case Constant.BC_CONNECTION_OFF:
77+
if (webSocketListeners == null || Global.noConnection) return;
78+
79+
Global.noConnection = true;
80+
for (WSResponseHandler webSocketListener : webSocketListeners){
81+
webSocketListener.onFailed(Constant.NO_INTERNET, Constant.NO_INTERNET_ERROR_CODE);
82+
}
83+
Log.d(TAG, "Connection Off");
84+
break;
85+
case Constant.BC_CONNECTION_ON:
86+
Log.d(TAG, "Connection On");
87+
break;
88+
default:
89+
break;
90+
}
91+
}
92+
};
5093
public void connect() {
5194
Global.streamChat.setClientID(null);
5295
client = new OkHttpClient();
@@ -74,9 +117,7 @@ public void run() {
74117
webSocket.send("");
75118
}
76119
} finally {
77-
// 100% guarantee that this always happens, even if
78-
// your update method throws an exception
79-
int interval = Global.noConnection ? Constant.HEALTH_CHECK_INTERVAL / 3 : Constant.HEALTH_CHECK_INTERVAL;
120+
int interval = Global.noConnection ? Constant.HEALTH_CHECK_INTERVAL / 4 : Constant.HEALTH_CHECK_INTERVAL;
80121
mHandler.postDelayed(mHealthChecker, interval);
81122
}
82123
}
@@ -159,12 +200,17 @@ public void onFailure(WebSocket webSocket, Throwable t, Response response) {
159200

160201
clearWSClient();
161202
if (webSocketListeners == null) return;
162-
for (WSResponseHandler webSocketListener : webSocketListeners)
163-
webSocketListener.onFailed(t.getMessage(), t.hashCode());
164-
203+
for (WSResponseHandler webSocketListener : webSocketListeners){
204+
if (t != null){
205+
webSocketListener.onFailed(t.getMessage(), t.hashCode());
206+
}else{
207+
webSocketListener.onFailed("Unknown", Constant.NO_INTERNET_ERROR_CODE);
208+
}
209+
}
165210
}
166211
}
167212

213+
168214
public void clearWSClient() {
169215
try {
170216
client.dispatcher().cancelAll();

library/src/main/java/com/getstream/sdk/chat/utils/ConnectionChecker.java

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -13,36 +13,15 @@ public class ConnectionChecker {
1313
private static Handler connectionCheckHandler = new Handler();
1414
private static Context context;
1515

16-
public static void connectionCheck(Context context) {
17-
ConnectionChecker.startConnectionCheckRepeatingTask(context.getApplicationContext());
16+
public static void startConnectionCheck(Context context) {
17+
ConnectionChecker.startConnectionCheckRepeatingTask(context);
1818
}
1919

2020
private static Runnable runnableConnectionCheck = new Runnable() {
2121
@Override
2222
public void run() {
2323
try {
24-
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
25-
boolean noConnection = !(activeNetwork != null && activeNetwork.isConnectedOrConnecting());
26-
if (noConnection && noConnection != Global.noConnection) {
27-
Global.noConnection = noConnection;
28-
Intent broadcast = new Intent();
29-
broadcast.addCategory(Intent.CATEGORY_DEFAULT);
30-
31-
if (Global.noConnection) {
32-
broadcast.setAction(Constant.BC_CONNECTION_OFF);
33-
} else {
34-
broadcast.setAction(Constant.BC_CONNECTION_ON);
35-
}
36-
37-
context.sendBroadcast(broadcast);
38-
Log.d(TAG, "Connection: " + !Global.noConnection);
39-
}
40-
41-
42-
// if (Global.noConnection) {
43-
// Global.channels = new ArrayList<>();
44-
// if (Global.streamChat != null) Global.streamChat.setClientID(null);
45-
// }
24+
isConnection(context.getApplicationContext());
4625
} finally {
4726
connectionCheckHandler.postDelayed(runnableConnectionCheck, 1000 * 3);
4827
}
@@ -51,12 +30,32 @@ public void run() {
5130

5231
private static void startConnectionCheckRepeatingTask(Context context) {
5332
stopConnectionCheckRepeatingTask();
54-
ConnectionChecker.context = context;
55-
connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
33+
ConnectionChecker.context = context.getApplicationContext();
34+
connectivityManager = (ConnectivityManager) ConnectionChecker.context.getSystemService(ConnectionChecker.context.CONNECTIVITY_SERVICE);
5635
runnableConnectionCheck.run();
5736
}
5837

5938
public static void stopConnectionCheckRepeatingTask() {
6039
connectionCheckHandler.removeCallbacks(runnableConnectionCheck);
6140
}
41+
42+
private static void isConnection(Context context) {
43+
if (connectivityManager == null)
44+
connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
45+
46+
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
47+
boolean noConnection = !(activeNetwork != null && activeNetwork.isConnectedOrConnecting());
48+
49+
if (noConnection != Global.noConnection) {
50+
Intent broadcast = new Intent();
51+
broadcast.addCategory(Intent.CATEGORY_DEFAULT);
52+
Log.d(TAG,"No connection: " + noConnection + ": Global No connection: " + Global.noConnection);
53+
if (noConnection) {
54+
broadcast.setAction(Constant.BC_CONNECTION_OFF);
55+
} else {
56+
broadcast.setAction(Constant.BC_CONNECTION_ON);
57+
}
58+
context.sendBroadcast(broadcast);
59+
}
60+
}
6261
}

library/src/main/java/com/getstream/sdk/chat/utils/Constant.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ public final class Constant {
2929
public static final String BC_RECONNECT_CHANNEL = "BC_RECONNECT_CHANNEL";
3030
public static final String BC_CONNECTION_OFF = "BC_CONNECTION_OFF";
3131
public static final String BC_CONNECTION_ON = "BC_CONNECTION_ON";
32+
33+
public static final String NO_INTERNET = "No internet connection!";
34+
public static final int NO_INTERNET_ERROR_CODE = 10001;
3235
// pagination
3336
public static final int CHANNEL_LIMIT = 30;
3437
public static final int CHANNEL_MESSAGE_LIMIT = 25;

library/src/main/java/com/getstream/sdk/chat/view/activity/ChatActivity.java

Lines changed: 30 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@
5151
import com.getstream.sdk.chat.rest.apimodel.response.EventResponse;
5252
import com.getstream.sdk.chat.rest.apimodel.response.GetRepliesResponse;
5353
import com.getstream.sdk.chat.rest.apimodel.response.MessageResponse;
54-
import com.getstream.sdk.chat.utils.ConnectionChecker;
5554
import com.getstream.sdk.chat.utils.Constant;
5655
import com.getstream.sdk.chat.utils.Global;
5756
import com.getstream.sdk.chat.utils.PermissionChecker;
@@ -113,14 +112,13 @@ protected void onCreate(Bundle savedInstanceState) {
113112
super.onCreate(savedInstanceState);
114113

115114
binding = DataBindingUtil.setContentView(this, R.layout.activity_chat);
116-
Global.webSocketService.setWSResponseHandler(this);
115+
Global.webSocketService.setWSResponseHandler(this, getApplicationContext());
117116
singleConversation = (Global.streamChat.getChannel() != null);
118117
init();
119118
if (!singleConversation) {
120119
setDeliverLastMessage();
121120
configUIs();
122121
} else {
123-
ConnectionChecker.connectionCheck(getApplicationContext());
124122
if (TextUtils.isEmpty(Global.streamChat.getClientID())) {
125123
binding.setShowMainProgressbar(true);
126124
} else {
@@ -140,8 +138,6 @@ public void onResume() {
140138

141139
IntentFilter filter = new IntentFilter();
142140
filter.addAction(Constant.BC_RECONNECT_CHANNEL);
143-
filter.addAction(Constant.BC_CONNECTION_OFF);
144-
filter.addAction(Constant.BC_CONNECTION_ON);
145141
filter.addCategory(Intent.CATEGORY_DEFAULT);
146142
registerReceiver(receiver, filter);
147143
}
@@ -158,10 +154,8 @@ public void onStop() {
158154
unregisterReceiver(receiver);
159155
} catch (IllegalArgumentException e) {
160156
if (e.getMessage().contains("Receiver not registered")) {
161-
// Ignore this exception. This is exactly what is desired
162157
Log.w(TAG, "Tried to unregister the reciver when it's not registered");
163158
} else {
164-
// unexpected, re-throw
165159
throw e;
166160
}
167161
}
@@ -244,7 +238,7 @@ private void initReconnection() {
244238
channel = channelResponse.getChannel();
245239
channelMessages = channelResponse.getMessages();
246240
checkEphemeralMessages();
247-
messageFunction = new MessageFunction(this.channelResponse);
241+
messageFunction = new MessageFunction(this.channelResponse, this);
248242
sendFileFunction = new SendFileFunction(this, binding, channelResponse);
249243
checkReadMark();
250244
noHistory = channelMessages.size() < Constant.CHANNEL_MESSAGE_LIMIT;
@@ -576,6 +570,10 @@ public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
576570
* Send Message - Send a message to this channel
577571
*/
578572
public void sendMessage(View view) {
573+
// if (Global.noConnection) {
574+
// Utils.showMessage(this, Constant.NO_INTERNET);
575+
// return;
576+
// }
579577
if (binding.etMessage.getTag() == null) {
580578
sendNewMessage(binding.etMessage.getText().toString(), sendFileFunction.getSelectedAttachments(), null);
581579
} else
@@ -605,7 +603,7 @@ public void onSuccess(MessageResponse response) {
605603
@Override
606604
public void onFailed(String errMsg, int errCode) {
607605
binding.tvSend.setEnabled(true);
608-
Log.d(TAG, "Failed Sending message: " + errMsg);
606+
Utils.showMessage(ChatActivity.this, errMsg);
609607
}
610608
});
611609
initSendMessage();
@@ -632,13 +630,14 @@ public void onSuccess(MessageResponse response) {
632630
@Override
633631
public void onFailed(String errMsg, int errCode) {
634632
binding.tvSend.setEnabled(true);
633+
Utils.showMessage(ChatActivity.this, errMsg);
635634
}
636635
});
637636
}
638637

639638
public void resendMessage(Message message) {
640639
if (Global.noConnection) {
641-
Utils.showMessage(this, "No internet connection!");
640+
Utils.showMessage(this, Constant.NO_INTERNET);
642641
return;
643642
}
644643
handleAction(message);
@@ -1126,38 +1125,6 @@ public void onFailed(String errMsg, int errCode) {
11261125
binding.setShowMainProgressbar(false);
11271126
}
11281127

1129-
private BroadcastReceiver receiver = new BroadcastReceiver() {
1130-
@Override
1131-
public void onReceive(Context context, Intent intent) {
1132-
switch (intent.getAction()) {
1133-
case Constant.BC_RECONNECT_CHANNEL:
1134-
Log.d(TAG, "Reconnection!");
1135-
channelResponse = Global.getChannelResponseById(channel.getId());
1136-
Global.setStartDay(channelResponse.getMessages(), null);
1137-
initReconnection();
1138-
// Check Ephemeral Messages
1139-
checkEphemeralMessages();
1140-
1141-
runOnUiThread(() -> {
1142-
setDeliverLastMessage();
1143-
configUIs();
1144-
if (isThreadMode())
1145-
configThread(thread_parentMessage);
1146-
});
1147-
1148-
break;
1149-
case Constant.BC_CONNECTION_OFF:
1150-
binding.setNoConnection(true);
1151-
Log.d(TAG, "Connection Off");
1152-
break;
1153-
case Constant.BC_CONNECTION_ON:
1154-
Log.d(TAG, "Connection On");
1155-
break;
1156-
default:
1157-
break;
1158-
}
1159-
}
1160-
};
11611128
// Event Listener
11621129

11631130
/**
@@ -1354,6 +1321,27 @@ private void reactionEvent(Event event) {
13541321
}
13551322
}
13561323

1324+
private BroadcastReceiver receiver = new BroadcastReceiver() {
1325+
@Override
1326+
public void onReceive(Context context, Intent intent) {
1327+
if (!intent.getAction().equals(Constant.BC_RECONNECT_CHANNEL))
1328+
return;
1329+
1330+
Log.d(TAG, "Reconnection!");
1331+
channelResponse = Global.getChannelResponseById(channel.getId());
1332+
Global.setStartDay(channelResponse.getMessages(), null);
1333+
initReconnection();
1334+
// Check Ephemeral Messages
1335+
checkEphemeralMessages();
1336+
1337+
runOnUiThread(() -> {
1338+
setDeliverLastMessage();
1339+
configUIs();
1340+
if (isThreadMode())
1341+
configThread(thread_parentMessage);
1342+
});
1343+
}
1344+
};
13571345
// endregion
13581346

13591347
// region Footer Event

0 commit comments

Comments
 (0)