AsyncTask用于将数据发送到服务器

时间:2013-03-20 12:45:14

标签: android android-asynctask

我正在写一个AsyncTask,希望在后台连续将数据发送到服务器。我在onCreate()的{​​{1}}中调用了它。但它没有用。显示MainActivity中的吐司然后没有任何反应。

onPreExecute()

请帮忙。 谢谢。

4 个答案:

答案 0 :(得分:3)

对于一个问题,您需要更具体地了解正在发生的事情。但是,您不希望这样做。 AsyncTask用于短期操作/根据Docs

  

理想情况下,AsyncTasks应该用于短操作(最多几秒钟。)如果需要保持线程长时间运行,强烈建议您使用java.util.concurrent提供的各种API。 pacakge,如Executor,ThreadPoolExecutor和FutureTask。

你有while(true)的无限循环,这很少是一个好主意。我建议你重新考虑一下你是怎么做到的。您可以设置TimerAlarmManagerService,但我建议您不要使用AsyncTask

答案 1 :(得分:1)

您可以使用服务连续上传数据。我提供在服务器上连续运行后台和上传数据的代码。

您只需拨打此服务:

startService(new Intent(this,BackgroundService.class));

还在Android清单文件中添加条目

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class BackgroundService extends IntentService
{
    private static final String TAG = "BackgroundService";
    Context mContext = null;

    final static int SERVICE_NAME = 1;
    int WORK_TYPE;

    public BackgroundService()
    {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {

        mContext = getBaseContext();
        WORK_TYPE = SETTING;
        new BackgroundTask(mContext).execute();
    }

    public class BackgroundTask extends AsyncTask<String, String, Void>
    {
        Context mContext = null;

        public BackgroundTask(Context context)
        {
            mContext = context;
        }

        protected void onPreExecute()
        {
        }

        protected Void doInBackground(final String... args)
        {
            switch (WORK_TYPE)
            {
                case SETTING:
                String input = "what ever text data post on server";
                response = sendDataToServer(input);
                JsonUtils.parseServerData(response, hashMapObj);
                break;
            }
            return null;
        }

        protected void onPostExecute(final Void unused)
        {
            switch (WORK_TYPE)
            {
                case SETTING:
                    if (!"".equalsIgnoreCase(response) && response != null)
                    {
                        DeviceUtils.deviceRegistration(hashMapObj, mContext);   
                    }
                    callService(SERVICE_NAME);
                    break;
            }
        }
    }

    public void callService(int work)
    {
        WORK_TYPE = work;
        new BackgroundTask(mContext).execute();
    }


    public String sendDataToServer(String data)
    {
        StringBuffer sb = new StringBuffer("");
        String serverUrl = "http://67.23.166.35:80/android/insert.php" ;
        try
        {
            URL url = new URL();
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(6 * 10 * 1000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestMethod("POST");

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = "";
            while ((line = rd.readLine()) != null)
            {
                // Process line...
                sb.append(line);
            }

            wr.close();
            rd.close();
            return sb.toString();
        }
        catch (Exception e)
        {
            Log.d("Exception : ", e.getStackTrace().toString());
        }

        return sb.toString();
    }}

答案 2 :(得分:0)

我注意到你在asyncTask中的参数都是无效的尝试将第一个参数更改为String当然更改后面的do参数作为String然后将你的类调用到你的onCreate。请将此作为参考

public class reqDataREST extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... arg0) {
    // TODO Auto-generated method stub

    HttpClient client = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(
            "http://icommute-ph.com/api/v1/todos/");

    try {
    // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("Name", tstData.getText().toString()));
                postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        BasicHttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());

    // Execute HTTP Post Request
        HttpResponse response = client.execute(postRequest, httpContext);
        //int statusCode = response.getStatusLine().getStatusCode();
    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
        // TODO Auto-generated catch block
    }
    catch (IOException e) {
        e.printStackTrace();
        // TODO Auto-generated catch block
    }
    return null;
}

}

答案 3 :(得分:0)

验证您的设备具有互联网访问权限,并且已在AndroidManiest.xml文件中授予了互联网访问权限。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />