例如:你要做一些需要几秒钟的事情,但不想冻结你的UI,对吧?您可以使用AsyncTask,但不想创建外部(或内部(类来解决小的冻结问题。
那么,一个好的练习能做到吗?
package com.example.stackoverflowsandbox;
import android.os.AsyncTask;
public class Foo {
// E.g. before call foo method you change you Activity to loading state.
private void foo() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground( final Void ... params ) {
// something you know that will take a few seconds
return null;
}
@Override
protected void onPostExecute( final Void result ) {
// continue what you are doing...
Foo.this.continueSomething();
}
}.execute();
}
private void continueSomething() {
// some code...
}
}
当我压缩位图并循环使用大数组来更新项目中的一些数据时,我遇到过这种情况。
是的,但不是你这样做的。
请记住,启动Honeycomb时AsyncTasks的默认执行模型是serial:
new AsyncTask<Void, Void, Void>() {
....
....
}.execute(); <------ serial execution
相反,使用线程池执行器:
new AsyncTask<Void, Void, Void>() {
....
....
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null); <------ parallel execution