gpt4 book ai didi

android - 使用什么代替 AsyncTask 来为长时间运行的操作更新 UI

转载 作者:太空狗 更新时间:2023-10-29 12:43:28 24 4
gpt4 key购买 nike

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

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

AsyncTasks should ideally be used for short operations (a few seconds at the most.

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

最佳答案

您可以使用处理程序:

关键思想是创建一个新的 Thread,它使用 Handler 来更新 UI(因为您无法从非 UI 线程的 Thread 更新 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();
}
};
}

关于android - 使用什么代替 AsyncTask 来为长时间运行的操作更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21760463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com