我是android開發中的新手,我正在做一個應用程序,需要每X時間自動連接到webservice。例如,連接以每30秒檢索一次數據,而無需用戶的交互。Android:自動連接到webservice,無需用戶干預的最佳方式
我試過用android.os.Handler,但是這個對象的問題是它在ui線程中運行,所以當連接需要很長時間時UI凍結... 我發現的唯一方法是做到這一點是使用asynctast和onPostexecute()再次調用相同的AsyncTask對象,這樣的事情:
公共類ScheduledAsyncTask擴展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();
}
}
這個偉大的工程,但我屁股梅不是最好的辦法。所有建議都歡迎。
由於提前,
新實例從我身邊:
我覺得這是做什麼我想要做的最好的辦法,檢查它請:
我的代碼:
公共類MainScheduledTime延伸活動實現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) {
}
}