异步任务doInBackground仅被调用一次

时间:2013-12-28 08:01:59

标签: android android-asynctask

我正在通过按下按钮到本地网络服务器来发布我手机的当前位置。 Web服务器正确接收POST。

但是,出于某种原因,我只能向服务器发送一个位置,之后Async Task只被调用一次。 编辑:调用异步任务,但不调用doInBackground方法。 - 然后按下每个后续按钮按下任务未到达。我确实在上面的链接中读到它只能被调用一次,但我认为每个对象只有一次 - 而且出于某种原因,在我改变了一些东西之前这一切都工作得很好而且都搞砸了。

我需要能够在几分钟内从手机发送数百个这样的请求,因此这里的任何指导都很有用。谢谢!

package com.spencer.gps;

import android.app.Activity;
import android.content.Context;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity{
    private TextView latituteField;
    private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;
    LocationManager mlocManager = null;
    LocationListener mlocListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();
        mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);

        final Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               getAndSendLocation();
            }
        });

        /*new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getAndSendLocation();
                    }
                });
            }
        }, 0, 1000);*/
    }

    public void getAndSendLocation() {

        final TextView latitudeField = (TextView)  findViewById(R.id.lat);
        final TextView longitudeField = (TextView) findViewById(R.id.longit);

        if (mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            latitudeField.setText("Latitude: " + MyLocationListener.latitude + '\n');
            longitudeField.setText("Longitude: " + MyLocationListener.longitude + '\n');

            new doPost().execute(MyLocationListener.latitude, MyLocationListener.longitude);

        } else {
            latitudeField.setText("GPS is not turned on...");
            longitudeField.setText("GPS is not turned on...");
        }
    }



    public class doPost extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] objects) {
            double lat = (Double) objects[0];
            double longit = (Double) objects[1];

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.110:3000/coord");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("lat", Double.toString(lat)));
                nameValuePairs.add(new BasicNameValuePair("long", Double.toString(longit)));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }

            return null;
        }
    }

    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();

    }
} 

1 个答案:

答案 0 :(得分:1)

AsyncTask.execute()

根据文件:

  

注意:此函数根据平台版本为单个后台线程或线程池调度队列上的任务。首次引入时,AsyncTasks在单个后台线程上串行执行。从DONUT开始,这被改为一个线程池,允许多个任务并行运行。启动HONEYCOMB,任务将恢复在单个线程上执行,以避免由并行执行引起的常见应用程序错误。如果您真的想要并行执行,可以使用THREAD_POOL_EXECUTOR使用此方法的executeOnExecutor(Executor,Params ...)版本;但是,请在那里查看有关其使用的警告。

所以,你应该这样打电话:

 new doPost(). executeOnExecutor(AsyncTask. THREAD_POOL_EXECUTOR , MyLocationListener.latitude, MyLocationListener.longitude);

这将并行执行所有线程,并对此方法进行API 11检查。

希望有所帮助。 :)

相关问题