如何在Android Studio中每X秒运行一次AsyncTask?

时间:2015-10-02 09:22:47

标签: android timer android-asynctask intervals

我正在执行从我的网络主机获取数据的AsyncTask。为了让我能够检索数据,我需要重新打开我的应用程序。我怎样才能每秒获取数据?我知道AsyncTask只能执行一次,但我不仅需要我的应用程序,还要了解这个问题。希望向你们学习。

这是我的代码:

class AsyncDataClass2 extends AsyncTask<String, Void, String>
{

    @Override
    protected String doInBackground(String... params) {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(params[0]);

        String jsonResult = "";
        try
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", params[1]));
            nameValuePairs.add(new BasicNameValuePair("password", params[2]));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);
            jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }

        catch (IOException e)
        {
            e.printStackTrace();
        }
        return jsonResult;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String result) {

        if (result.equals("") || result == null)
        {
            Toast msg = Toast.makeText(MapsActivity.this, "connection failed", Toast.LENGTH_LONG);
            msg.setGravity(Gravity.CENTER, 0, 0);
            msg.show();
        }

        else
        {
            Toast msg = Toast.makeText(MapsActivity.this, "connected", Toast.LENGTH_LONG);
            msg.setGravity(Gravity.CENTER,0,0);
            msg.show();
        }

        try {
            JSONArray json = new JSONArray(result);

            for (int i = 0; i < json.length(); i++) {
                JSONObject e = json.getJSONObject(i);
                String point = e.getString("Point");

                String[] point2 = point.split(",");

                String devStatus = e.getString("Status");   //now, let's process the Status...
                String strOwner = e.getString("Owner");     //now, let's process the owner...

                //==============================================================================


                if (devStatus.equals("fire")) {
                    IsThereFire=true;
                }

            } //---End of FOR LOOP---//


        }//---end of TRY---//

        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is)
    {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        try
        {
            while ((rLine = br.readLine()) != null)
            {
                answer.append(rLine);
            }
        }

        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return answer;
    }
}

编辑:

先生,这是我用过的计时器..

///---CODE for the TIMER that ticks every second and synch to database to update status---///
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // HERE IS THE ACTUAL CODE WHERE I CALL THE ASYNCDATACLASS2
                            AsyncDataClass2 performBackgroundTask = new AsyncDataClass2();
                            // PerformBackgroundTask this class is the class that extends AsynchTask
                            performBackgroundTask.execute();
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
    //---------------------------------------------------------------//

4 个答案:

答案 0 :(得分:1)

如果需要以固定的时间间隔执行任务,可以使用带TimerTask的Timer。它运行在与UI线程不同的线程上,这意味着您可以直接在其中运行http调用。您可以找到文档here

答案 1 :(得分:0)

我认为这样做并不是一个好主意,但你可以做到这一点,当然只需要一个简单的TimerTask(教程there

基本上,它看起来像这样:

public class MyTimerTask extends TimerTask {
    @Override
    public void run() {
        // Just start your AsyncTask and proceed, I didn't adapt the code to your task
        new AsyncDataClass2().execute()
    }
}

你的逻辑称之为:

TimerTask timerTask = new MyTimerTask();
 // They're ms: 1000ms = 1s
 timer.scheduleAtFixedRate(timerTask, 0, 1000);
 timer.start();

您在销毁Fragment / Activity

时取消它
timer.cancel();

答案 2 :(得分:0)

我认为您应该尝试使用TimerTask或作业调度程序。

可以找到有关作业调度程序的大量信息herehere

答案 3 :(得分:0)

检查一下:

startTimer();

然后在@protocol中写下:

CustomView

虽然,您应该考虑其他人的评论,他们有意义,在AsyncTask中每秒都要求从Web服务器发送更新,这不是一件好事。