AsyncTask每隔10秒检查一次新数据

时间:2014-10-16 10:59:17

标签: android json

我正在使用AsyncTaskdata获取server,如果检查new data是否可用,或update更改existing data怎么办?每隔 10秒

public class MainActivity extends Activity {

    CenterLockHorizontalScrollview centerLockHorizontalScrollview;
    ArrayList<Actors> actorsList;   
    ActorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        actorsList = new ArrayList<Actors>();
        new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");

        centerLockHorizontalScrollview = (CenterLockHorizontalScrollview) findViewById(R.id.scrollView);                              
    }


    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                //------------------>>
                HttpGet httppost = new HttpGet(urls[0]);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);


                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("actors");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Actors actor = new Actors();

                        actor.setName(object.getString("name"));
                        Log.d("Name:", object.getString("name"));
                        actor.setImage(object.getString("image"));
                        Log.d("Image:", object.getString("image"));

                        actorsList.add(actor);
                    }
                    return true;
                }

                //------------------>>

            } catch (ParseException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        protected void onPostExecute(Boolean result) {
    dialog.cancel();           
    if(result == false)
        Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
    if(actorsList != null) {
        adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);      
        centerLockHorizontalScrollview.setAdapter(MainActivity.this, adapter); 
    }

    }

}

2 个答案:

答案 0 :(得分:2)

您可以使用刷新方法进行检查。

 void refresh(boolean b){
    if(b){
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            refresh(true);
        }
    }, 10*1000);
    }
}

在你的oncreate中调用这个方法

 new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
 refresh(true);

答案 1 :(得分:2)

有几种方法可以解决这个问题。最合适的一个将主要取决于规格,设计和架构决定为你的应用程序。

1) Java的TimerTask。

import java.util.Timer;
Timer timer = new Timer(); 

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // work
  }
}, 0, 10*1000); // 0 - time before first execution, 10*1000 - repeating of all subsequent executions

timer.cancel(); //cancels the timer and all schedules executions

2) Android的处理程序。功能强大,常用于您所要求的内容。但是,您必须确保您没有嵌套处理程序。更多信息here;它或多或少地描述了使用处理程序寻找的解决方案。

3) Android的预定闹钟。即使这会起作用,如果你真的想每隔10秒运行一次,那么,我会说这可能不是最好的解决方案。但无论如何,这允许您注册Android的警报,这会让您有时间在BroadcastReceiver中运行某些内容,这会在警报触发时触发。这里有很多内容,但您可以在此处了解如何安排闹钟:https://developer.android.com/training/scheduling/alarms.html