【问题标题】:Android Timed Async TaskAndroid 定时异步任务
【发布时间】:2014-02-12 08:39:09
【问题描述】:

您好,目前我有以下使用 Asycn 任务和计时器的代码。

我的异步任务基本上是尝试从 URL 发送 HTTP GET 方法,其中来自服务器的响应可能因连接和负载而异。

我想做的是有一个定时异步任务。在哪里,它会每隔 X 秒安排一个 AsyncTask,但是如果当前有一个 Async 任务正在进行中,我必须先杀死它。然后开始一个新的。

这是我目前拥有的代码:

private static boolean running = false;
Timer myTimer;
protected void onCreate(Bundle savedInstanceState) {
        /* REST OF CODE OMITTED */
        MyTimerTask myTask = new MyTimerTask();
        myTimer = new Timer();
        myTimer.schedule(myTask, 0, 10000);
}

/* REST OF CODE OMITTED */

private class MyTimerTask extends TimerTask {
    public void run() {
        if(!running){
            Log.i("TAG", "NEW TIMER STARTED.");
            RetrieveChatMessage task = new RetrieveChatMessage();
            task.execute();
            running = true;
        }else{
            running = false;
        }
    }
}

private class RetrieveChatMessage extends AsyncTask<String, Void, ArrayList<Chat>> {
    @Override
    protected ArrayList<Chat> doInBackground(String... params) {
        // TODO Auto-generated method stub
        ArrayList<Chat> cList = null;
        String jResult = null;

        Log.i("TAG", "RETRIEVING CHAT MESSAGE");

        try {
            jResult = ((new HttpRetriever())).getChatList(mAccount.email, mAccount.passwd);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            if(jResult != null){
                Log.i("TAG", "JSON DATA: " + jResult);
                cList = (new ChatHandlers()).getChatList(jResult);
            }else{
                cList = null;
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("TAG", "JSON Exception " + e.toString());
        }

        return cList;
    }

    @Override
    protected void onPostExecute(final ArrayList<Chat> result) {
        Log.i("TAG", "ON POST EXECUTE");
        if(result != null){
              // Do something here
        }
    }
}

老实说,上面的代码存在一些小问题: 1. 似乎是随机执行异步,而不是每 10 秒执行一次。 2. 当我去另一个活动时,它在某种程度上阻止了其他异步任务完成它的工作(它也试图从服务器检索 JSON 响应)。

我不太担心后面的问题(这不是我要问的问题)。我只是想知道如何有一个适当的定时异步任务。谁能给我指个方向。

谢谢。

编辑#1:

在阅读了@thepoosh 的评论后,我尝试了以下方法(我把它放在 onCreate 中):

scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
    public void run() {
        // Parsing RSS feed:
        // myFeedParser.doSomething();
        Log.w("THUMBQOO", "NEW TASK STARTED");
        retrieveChat();
    }
  }, 0, 15, TimeUnit.SECONDS);

结果:我有一个一致的任务执行。但是,似乎retrieveChat();在第一次执行后永远不会被调用。

【问题讨论】:

  • 你应该使用ScheduledPoolExecutor而不是Timer
  • 您能详细说明一下吗?也许举个例子?谢谢

标签: android asynchronous android-asynctask


【解决方案1】:

其实AsyncTask不用于长操作。检查Here

你应该使用Thread,它使用一个接口来通知UI,或者你可以简单地使用Handler,这是android中最受青睐的方式。只需每 10 秒重复执行一项任务

handler.postDelayed(new Runnable() {
@Override
public void run() {
  // do work
  handler.postDelayed(10000);
}
}, 10000);

【讨论】:

    【解决方案2】:

    声明一个Handler对象来维护未来的任务执行器...

    private Handler mTimerHandler = new Handler();
    

    写一个线程来执行你未来的任务...

    private Runnable mTimerExecutor = new Runnable() {
    
        @Override
        public void run() {
    
            //write your code what you want to do after the specified time elapsed
    
            if(!running){
                RetrieveChatMessage task = new RetrieveChatMessage();
                task.execute();
                running = true;
            }else{
                running = false;
            }
    
        }
    };
    

    使用 hanlder 调用你未来的 tast executor...

    mTimerHandler.postDelayed(mTimerExecutor, 10000);
    

    你可以通过这个随时取消你未来的任务执行者...

    mTimerHandler.removeCallbacks(mTimerExecutor);
    

    【讨论】:

      【解决方案3】:

      我不确定这是否是实现这一目标的好方法(我的回答如下):

      使用一个处理程序,创建一个处理程序线程并不断向这个处理程序发送消息。 对于处理程序“handleMessage”方法,您可以执行任务并再次将消息发送回 MessageQueue。

      HandlerThread thread = new HandlerThread(<name>);
      thread.start();
      
      Looper looper = thread.getLooper();
      CustomHandler handler = new CustomHandler(looper);
      
      // The CustomHandler class
      class CustomHandler extends Handler {
      
            public CustomHandler(Looper looper) {
                super(looper);
            }
      
            @Override
            public void handleMessage(Message msg) {
                //Do your operation here
      
                handler.sendEmptyMessageDelayed(msg, <delayTime>);
            }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-26
        • 1970-01-01
        • 2019-02-19
        • 1970-01-01
        • 2021-07-05
        • 2016-11-23
        • 2013-11-14
        相关资源
        最近更新 更多