Android:无需用户交互即可自动连接到Web服务的最佳方法

问题描述

|| 我是android开发的新手,我正在做一个需要每X时间自动连接到Web服务的应用程序。例如,connect每30秒检索一次数据,而无需用户交互。 我尝试使用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扩展Activity实现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();
            }
        }
    },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) {

} 
}     

解决方法

您应该在“服务”中进行网络服务调用。然后您可以使用AlarmManager计划执行服务     ,您可以简单地使用常规线程。 AsyncTask不是用于无限循环的。