0

我正在编写一个AsyncTask有望在后台连续将数据发送到服务器的程序。我已将其称为onCreate(). MainActivity但它不起作用。吐司onPreExecute()显示然后什么也没有发生。

private class MyAsync extends AsyncTask<Void, Void, Void>
 {
      @Override
      protected void onPreExecute() 
      {
          Toast.makeText(getApplicationContext(),"1", Toast.LENGTH_LONG).show();
            // update the UI immediately after the task is executed
            super.onPreExecute();
      }

          @Override
          protected Void doInBackground(Void... params)
          {
             // Toast.makeText(getApplicationContext(),"2", Toast.LENGTH_LONG).show();
              File file = new File(Environment.getExternalStorageDirectory(),"/BPCLTracker/gpsdata.txt");
              int i=0;

              RandomAccessFile in = null;

              try
              {
                  in = new RandomAccessFile(file, "rw");
              } 
              catch (FileNotFoundException e) 
              {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              //String line =null;
              while (true) 
              {
                HttpEntity entity=null;
                try 
                {
                    if (new GPSLoggerService().isInternetOn()) 
                    {
                            while ((line = in.readLine()) != null)
                            {

                                HttpClient client = new DefaultHttpClient();
                                String url = "http://67.23.166.35:80/android/insert.php";
                                HttpPost request = new HttpPost(url);
                                StringEntity se = new StringEntity(line);
                                se.setContentEncoding("UTF-8");
                                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                                entity = se;
                                request.setEntity(entity);
                                HttpResponse response = client.execute(request);
                                entity = response.getEntity();
                                i++;
                            }
                            if((line = in.readLine()) == null && entity!=null)
                            {
                                file.delete();
                                new MyAsync().execute();
                            }


                    }// end of if
                    else
                    {
                        Thread.sleep(60000);

                    } // end of else
                }// end of try
                catch (NullPointerException e1)
                {
                    e1.printStackTrace();
                } 
                catch (InterruptedException e2) 
                {
                    e2.printStackTrace();
                }
                catch (IOException e1) 
                {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }// end of while

      }//doinbackground

      @Override
      protected void onProgressUpdate(Void... values) {
         // Toast.makeText(getApplicationContext(),"3", Toast.LENGTH_LONG).show();
      }

      @Override
      protected void onPostExecute(Void result) {
          Toast.makeText(getApplicationContext(),"4", Toast.LENGTH_LONG).show();
      }

     }//AsyncTask

请帮忙。谢谢你。

4

4 回答 4

3

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

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

你有一个无限循环,while(true)这很少是一个好主意。我建议你重新考虑如何做到这一点。您可以设置 a Timer,AlarmManager或 aService但我建议您不要AsyncTask用于此

于 2013-03-20T12:50:50.140 回答
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();
    }}
于 2013-03-20T17:28:59.683 回答
0

我注意到您在 asyncTask 中的参数全部无效尝试将第一个参数更改为字符串,当然还将后台执行的参数更改为字符串,然后将您的类调用到您的 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;
}

}

于 2013-07-06T07:08:22.713 回答
0

验证您的设备是否可以访问 Internet,并且您已在 AndroidManiest.xml 文件中授予 Internet 访问权限。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2020-01-14T17:06:32.577 回答