TcpClient reconnect issue

  • Replies:0
  • OpenNot stickiedUnanswered

May 11, 2013 12:53:04 PM

Hi,
I am sending every 3 seconds gps location to server.

I am testing this application, for example, I manually switch off the Internet. Then the application does not connect again (I think it is blocked by the write function). My guess is that the problem lies in the fact that the disconnection occurs after the if statement.
When I'm doing step by step debugging and disable internet before "if", everything is ok, but if I disable it after "if", for example in second "if", app won't reconnect.
How to solve this problem?
1timer = new Timer();
2timer.scheduleAtFixedRate(new TimerTask()
3{
4 BufferedReader st = null;
5 public void run()
6 {
7 try {
8 st = new BufferedReader(new InputStreamReader(s.getInputStream()));
9 String response ="";
10
11
12 boolean test= false;
13 if (test=isConnected(getApplicationContext())){
14 Log.v("try","Send");
15 send(); // I think, here is problem
16 if ((response=st.readLine()) != null && response.length()>0){
17 Log.v("ok","received");
18 }
19 else{
20 connect(); // if for example server is off
21 }
22
23 }
24 else{
25 while(!isConnected(getApplicationContext())){
26 runData(true); // reenable internet connection
27 }
28 connect(); // connect again after reenabled internet
29 }
30 } catch (IOException e) {
31 e.printStackTrace();
32 } catch (Exception e) {
33 e.printStackTrace();
34 }
35 }
36}, 0, 3000);
37
38public void send() {
39 try {
40 DataOutputStream x = new DataOutputStream(s.getOutputStream());
41 x.writeBytes("ss\n"+latitude+"\n"+longitude+"\n");
42 }catch(SocketException e){
43 return;
44 } catch (IOException e) {
45 e.printStackTrace();
46 }
47
48}
49
50
51public void connect(){
52 try {
53 s = new Socket("192.168.1.100",20000);
54 } catch (UnknownHostException e) {
55 // TODO Auto-generated catch block
56 e.printStackTrace();
57 } catch (IOException e) {
58 // TODO Auto-generated catch block
59 e.printStackTrace();
60 }
61 }
62
63private void runData(boolean option) throws Exception{
64 ConnectivityManager dataManager;
65 dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
66 Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
67 dataMtd.setAccessible(option);
68 dataMtd.invoke(dataManager, option);
69 }
70//
71 public static boolean isConnected(Context context) {
72 ConnectivityManager connectivityManager = (ConnectivityManager)
73 context.getSystemService(Context.CONNECTIVITY_SERVICE);
74 NetworkInfo networkInfo = null;
75 if (connectivityManager != null) {
76 networkInfo = connectivityManager.getActiveNetworkInfo();
77 }
78
79 return networkInfo == null ? false : networkInfo.getState() == NetworkInfo.State.CONNECTED;
80 }