timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
BufferedReader st = null;
public void run()
{
try {
st = new BufferedReader(new InputStreamReader(s.getInputStream()));
String response ="";
boolean test= false;
if (test=isConnected(getApplicationContext())){
Log.v("try","Send");
send(); // I think, here is problem
if ((response=st.readLine()) != null && response.length()>0){
Log.v("ok","received");
}
else{
connect(); // if for example server is off
}
}
else{
while(!isConnected(getApplicationContext())){
runData(true); // reenable internet connection
}
connect(); // connect again after reenabled internet
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, 3000);
public void send() {
try {
DataOutputStream x = new DataOutputStream(s.getOutputStream());
x.writeBytes("ss\n"+latitude+"\n"+longitude+"\n");
}catch(SocketException e){
return;
} catch (IOException e) {
e.printStackTrace();
}
}
public void connect(){
try {
s = new Socket("192.168.1.100",20000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void runData(boolean option) throws Exception{
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
dataMtd.setAccessible(option);
dataMtd.invoke(dataManager, option);
}
//
public static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getActiveNetworkInfo();
}
return networkInfo == null ? false : networkInfo.getState() == NetworkInfo.State.CONNECTED;
}