以给定间隔执行异步任务

时间:2016-07-04 08:51:25

标签: java android post httprequest

我正在尝试设置一个每隔30秒创建并发送一次代码的应用。代码通过Web服务发送到数据库。 每当我运行应用程序时,它第一次运行,但如果30秒到期,则会出现以下错误:

app E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
                                                                         java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                             at android.os.AsyncTask$3.done(AsyncTask.java:299)
                                                                             at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
                                                                             at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
                                                                             at java.util.concurrent.FutureTask.run(FutureTask.java:239)
                                                                             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                                             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                                                                             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                                                                             at java.lang.Thread.run(Thread.java:856)
                                                                          Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
                                                                             at andreea.example.com.mobileapp.CodeGeneratorActivity$HttpAsyncTask.doInBackground(CodeGeneratorActivity.java:196)
                                                                             at andreea.example.com.mobileapp.CodeGeneratorActivity$HttpAsyncTask.doInBackground(CodeGeneratorActivity.java:181)
                                                                             at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                                             at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                                                                             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                                                                             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
                                                                             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
                                                                             at java.lang.Thread.run(Thread.java:856) 

行:

1. String post = POST(urls[0], my_code);

2. private class HttpAsyncTask extends AsyncTask<String, Void, String>

我包含了我使用的代码:

//POST request to add new user
public String POST(String url, CodeClass code)
{
    String result = "";
    InputStream inputStream = null;

    try{
        HttpClient httpclient;
        HttpPost httppost;
        ArrayList<NameValuePair>postParameters;
        httpclient = new DefaultHttpClient();
        httppost = new HttpPost(url);

        postParameters = new ArrayList<>();
        postParameters.add(new BasicNameValuePair("code", code_gen.getText().toString()));
        httppost.setEntity(new UrlEncodedFormEntity(postParameters));
        HttpResponse httpresponse = httpclient.execute(httppost);

        inputStream = httpresponse.getEntity().getContent();

        if(inputStream != null)
        {
            result = convertInputStreamToString(inputStream);
        }
        else
        {
            result = "Did not work";
        }


    }catch (Exception e)
    {
        e.getLocalizedMessage();
    }

    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    String auxcode = code_gen.getText().toString();
    final String url = my_url_builder();
    @Override
    protected String doInBackground(String... urls) {


        final ServiceHandler sh = new ServiceHandler();

        jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

        my_code = new CodeClass();
        my_code.setCode(auxcode);   //HERE!!


        String post = POST(urls[0], my_code);
        System.out.println(urls[0]+" This is the urls0");
        count++;
        return post;
    }
    // onPostExecute displays the results of the AsyncTask.
    protected void onPostExecute(String result) {

        HttpAsyncTask new_instance = new HttpAsyncTask();
        //new_instance.execute();
        Toast.makeText(getBaseContext(), "Yup", Toast.LENGTH_SHORT).show();
    }
}

我执行HttpAsyncTask:

 public void timer_code() {
    final Random rand = new Random();

    n = rand.nextInt(999999)+100000;
    code_gen.setText(String.valueOf(n));
    mytask = new HttpAsyncTask();
     test = my_url_builder();
   // mytask.execute(test);
    //System.out.println(nativePRNG.toString()+"Try code");

    new CountDownTimer(30000,1000){


        @Override
        public void onTick(long millisUntilFinished) {
            timer.setText(String.format(String.valueOf(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))));
        }

        public void onFinish()
        {
            n = rand.nextInt(999999)+100000;
            code_gen.setText(String.valueOf(n));

            //mytask = new HttpAsyncTask();
            callAsynchronousTask();
           // mytask.execute(test);

            this.start();
        }
    }.start();


}
  public void callAsynchronousTask() {

   Timer timer = new Timer();
   TimerTask doAsynchronousTask = new TimerTask() {
       @Override
       public void run() {
                   try {
                       HttpAsyncTask mytask = new HttpAsyncTask();
                       // PerformBackgroundTask this class is the class that extends AsynchTask
                       mytask.execute();
                   } catch (Exception e) {
                       // TODO Auto-generated catch block
                   }
               }
           };

   timer.schedule(doAsynchronousTask, 0, 30000); //execute in every 50000 ms
  }

2 个答案:

答案 0 :(得分:1)

看起来你没有用任何参数调用你的AsyncTask。

调用execute方法时,需要提供参数;例如:

public void run() {
    try {
        HttpAsyncTask mytask = new HttpAsyncTask();
        // PerformBackgroundTask this class is the class that extends AsynchTask
        mytask.execute( "https://www.google.com" );
    } catch (Exception ignore) {
        // TODO Auto-generated catch block
    }
}

作为助手,使用像Volley(https://developer.android.com/training/volley/index.html)这样的图书馆可能会更好。您可以使用Gradle compile 'com.android.volley:volley:1.0.0'依赖项将库包含在项目中。

这将允许您使用StringRequest获取字符串,这更简单(不需要使用InputStreams等)。或者RetroFit(https://github.com/square/retrofit),我最近一直在玩,并且非常喜欢。

希望这有帮助, GAV

答案 1 :(得分:1)

如果您正在运行app api 11+(蜂窝以上),请尝试此操作..

HttpAsyncTask mytask = new HttpAsyncTask();
    // PerformBackgroundTask this class is the class that extends AsynchTask
    mytask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

希望这会对你有所帮助。