Android: Best way to automatic connect to a webservice, without user interaction
I am new in android development and I am doing an application that needs to auto-connect to a webservice every X amount of time. For example connect to retrieve data every 30 seconds, without the user's interaction.
I tried with android.os.Handler but the problem with this Object is that it is running in the ui thread, so when the connection takes to much time the UI freeze... The only way that I found to do this is to use asynctast and in onPostexecute() call again to the same Asynctask Object, something like that:
public class ScheduledAsyncTask extends AsyncTasc {
doInBackground() {
Thread.sleep(30000); //30 seconds...
// connect to the server and retrieve data...
}
onPostExecute() {
// show new data to the user
ScheduledAsyncTask task = new ScheduledAsyncTask();
task.execute();
}
}
This works great but I assume is not the best way to do it. All suggestions are welcome.
Thanks in advance,
New Example from my side:
I think this is the best way to do what I want to do, check it please:
My Code:
public class MainScheduledTime extends Activity implements OnClickListener{
private int counter = 0;
private int counterTemp = 0;
private TextView label;
private Button button;
private Timer timer = new Timer();
private Handler counterHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
label = (TextView) findViewById(R.id.label);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
Thread.sleep(5000); // This emulates an expensive task. For Example: call a webservice and parse the data.
counterTemp++;
setCounter(counterTemp); /开发者_高级运维/ This methods needs to be synchronized
counterHandler.post(counterTask);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 0, 10000);
}
private Runnable counterTask = new Runnable() {
public void run() {
label.setText(getCounter() + "");
}
};
public synchronized int getCounter() {
return this.counter;
}
public synchronized void setCounter(int count) {
this.counter = count;
}
@Override
public void onClick(View arg0) {
}
}
you should do your webservice calls in a Service. then you can schedule the service for execution with the AlarmManager
You can simply use a regular Thread.
AsyncTask is not made for infinite loops.
精彩评论