I want to send a and b with get URL to example.com when I run it, it work one time.
I want send a and b during while condition is true. I use sleep so send data after 5 second continuously.
public class MapsActivity extends FragmentActivity
implements OnMapReadyCallback {
public a=0,b=0;
public btn=2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
connect();
} //end of onCreate
public void connect() {
new Thread(new Runnable() {
@Override
public void run() {
communication();
}
}).start();
}
public void communication() {
while(btn >0){
try {
btn++;
a++;
b++;
URL url = new URL("example.com"+ "?a=" +a+"&b="+b);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String data = "", line = "";
while ((line = bufferedReader.readLine()) != null) {
data += line + "\n";
}
sleep(5000);
} catch (MalformedURLException e) {
Log.e("error", e.toString());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of while
} //end of communication
}//end of class
I think Timer is better than sleep. You can try this:
Handler handler = new Handler();
Runnable sendRequest = new Runnable() {
public void run() {
// your code to send request
}
};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
handler.post(sendRequest);
}
}, 100, 5000);
I will recommend not to do it in the Activity class .
Create a Back ground service class which runs every n seconds , in your case lets say 5 .
Now create a Queue . In this Queue push the data , whenever the condition is true .
Once you background service starts running it will read from the queue and make the api calls with the data