[英]What to use instead of AsyncTask to update UI for long running operations
我创建了搜索android手机文件系统的应用程序,我想更新通知栏中的通知,其中包含当前正在搜索的文件的信息。
首先,我想使用AsyncTask,但后来发现它不应该用于长期运行的操作,我认为这是搜索文件系统的。 来自文档
理想情况下,AsyncTasks应该用于短操作(最多几秒钟)。
他们的建议是使用Executor,ThreadPoolExecutor和FutureTask。 但没有指定示例。 那么究竟应该做些什么才能正确实现呢? 有人能举个例子吗? 我不知道我是否应该有一些扩展AsyncTask的私有类,并将外部类的run方法放到doInBackground方法或其他东西..
您可以使用处理程序:
关键的想法是创建一个使用Handler
来更新UI的新Thread
(因为你无法从不是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();
}
};
}
你可以使用一个线程:
new Thread(new Runnable(){
@Override
public void run(){
//do operation
//make and show notifications. Notifications are thread safe
}
}});
您可以从工作线程通知,因为通知不会通过您的应用程序进程。 看这里
如果你必须发布到你的应用程序的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
。
我强烈建议你使用装载机:
http://developer.android.com/guide/components/loaders.html
它们构建在AsyncTasks之上,使AsyncTasks更易于在Activities中进行管理。
如果即使活动已关闭(后台操作),这应该继续运行,您应该使用在活动中绑定的服务。 请参阅本地服务文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.