I am working in android. I want to draw a comment window. in which I have a list View which shows comment retrieved from a API.
I want to call that API after 30 second again and again so i can show recent comments in my list view.
This is the code which is used to call my API.
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("192.168.1.127/CC/comment");
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Then put values in some text boxes.
}
I want to call this above code again and again after 10 second. Please help me in writing code. Your may give a short example to solve this type of problem. I have very short time and dont have time to search on google so please help how can i call API and change UI periodically ?
I want to call that API after 30 second again and again
You Should use Service with Broadcast receiver .
Service will do your Task in Background but will not provide any UI so you need to register with Broadcast receiver.
Check this Sample , this sample show how to repeat a task and update UI using Service and Broadcast receiver.
Also refer this tutorial for further reference.
You can simple use just following code:
// We need to use this Handler package
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this the same runnable code block again another 2 seconds
// 'this' is referencing the Runnable object
handler.postDelayed(this, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
You can remove the scheduled execution of a runnable with:
// Removes pending code execution
handler.removeCallbacks(runnableCode);
I have solved my problem like this:-
public class ClassName extends Activity
{
@Override
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
setContentView(R.layout.live_stream_layout);
handler.post(timedTask);
private Runnable timedTask = new Runnable(){
@Override
public void run()
{
//do your work here for calling API and UI
handler.postDelayed(timedTask ,2000 );
}};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.