使用什么而不是AsyncTask来更新长时间运行操作的UI

时间:2014-02-13 16:53:15

标签: android android-asynctask

我创建了搜索android手机文件系统的应用程序,我想更新通知栏中的通知,其中包含当前正在搜索的文件的信息。

首先,我想使用AsyncTask,但后来我发现它不应该用于长期运行的操作,我认为这是搜索文件系统的。来自文档

  

理想情况下,AsyncTasks应该用于短时间操作(几秒钟)   最多。

他们的建议是使用Executor,ThreadPoolExecutor和FutureTask。但没有指定示例。那么究竟应该做些什么才能正确实现呢?有人能举个例子吗?我不知道是否应该有一些扩展AsyncTask的私有类,并将外部类的run方法放到doInBackground方法或其他东西..

4 个答案:

答案 0 :(得分:2)

您可以使用处理程序:

关键的想法是创建一个使用Thread来更新UI的新Handler(因为你无法从不是UI线程的线程更新ui)。

官方文档:

http://developer.android.com/reference/android/os/Handler.html

public class YourClass extends Activity {

    private Button myButton;

    //create an handler
    private final Handler myHandler = new Handler();

    final Runnable updateRunnable = new Runnable() {
        public void run() {
            //call the activity method that updates the UI
            updateUI();
        }
    };


    private void updateUI()
    {
      // ... update the UI      
    }

    private void doSomeHardWork()
    {
        //.... hard work

        //  update the UI using the handler and the runnable
        myHandler.post(updateRunnable);
    }

    private OnClickListener buttonListener = new OnClickListener() {
        public void onClick(View v) {
            new Thread(new Runnable() { 

                    doSomeHardWork();

            }).start();
        }
    };
}

答案 1 :(得分:1)

您可以使用线程:

new Thread(new Runnable(){
    @Override
    public void run(){
        //do operation
        //make and show notifications. Notifications are thread safe
    }
}});

您可以从工作线程发出通知,因为通知未通过您的应用程序流程。 See here

如果您必须发布到应用程序的UI线程,那么您可以使用这样的处理程序:

//put this in the UI thread
Handler handler = new Handler();
//then within the thread code above
handler.post(new Runnable(){
    @Override
    public void run(){
        //code that you want to put on the UI thread, update views or whatever
    }
}});

修改:您可以使用工作线程中的runOnUiThread(...)而不是使用Handler

答案 2 :(得分:0)

我强烈建议你使用装载机:

http://developer.android.com/guide/components/loaders.html

它们构建于AsyncTasks之上,使AsyncTasks更容易在“活动”中进行管理。

答案 3 :(得分:0)

如果即使活动已关闭(后台操作),这应该继续运行,您应该使用您在活动中绑定的服务。 请参阅Local Service文档。