问题描述
在使用AsyncTaskLoader你将如何更新进度条显示的状态,因为它正在更新?通常情况下,你的回调等待删除完成后,却怎么办运行更新?你能让主线程(UI)查询数据,因为它是被设置还是什么?
When using a AsyncTaskLoader how would you update a progressbar showing the status as it is being updated? Normally you wait for the callback to remove when done, but how to do running updates?Would you let the main thread (ui) poll the data as it is being set or something?
编辑:我说的是 AsyncTaskLoader ,看看加载程序的一部分。这里是链接类:http://developer.android.com/reference/android/content/AsyncTaskLoader.html
I'm talking about AsyncTaskLoader, look at the loader part. Here is link to class: http://developer.android.com/reference/android/content/AsyncTaskLoader.html
我想使用它,因为它的未来:),我知道如何与AsyncTask的做到这一点。
I want to use it because its the future :), I know how to do this with AsyncTask.
推荐答案
您可以做到这一点与装载机,但你需要保持和您的活动更新WeakReference的:
You can do that with loaders, but you need to keep and update a WeakReference on your Activity :
public class LoaderTestActivity extends FragmentActivity implements LoaderCallbacks<Void> {
private static final int MAX_COUNT = 100;
private ProgressBar progressBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task_test);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setMax(MAX_COUNT);
AsyncTaskCounter.mActivity = new WeakReference<LoaderTestActivity>(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_async_task_test, menu);
return true;
}
public void onStartButtonClick(View v) {
startWork();
}
void startWork() {
getSupportLoaderManager().initLoader(0, (Bundle) null, this);
}
static class AsyncTaskCounter extends AsyncTaskLoader<Void> {
static WeakReference<LoaderTestActivity> mActivity;
AsyncTaskCounter(LoaderTestActivity activity) {
super(activity);
mActivity = new WeakReference<LoaderTestActivity>(activity);
}
private static final int SLEEP_TIME = 200;
@Override
public Void loadInBackground() {
for (int i = 0; i < MAX_COUNT; i++) {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(getClass().getSimpleName(), "Progress value is " + i);
Log.d(getClass().getSimpleName(), "getActivity is " + getContext());
Log.d(getClass().getSimpleName(), "this is " + this);
final int progress = i;
if (mActivity.get() != null) {
mActivity.get().runOnUiThread(new Runnable() {
@Override
public void run() {
mActivity.get().progressBar.setProgress(progress);
}
});
}
}
return null;
}
}
@Override
public Loader<Void> onCreateLoader(int id, Bundle args) {
AsyncTaskLoader<Void> asyncTaskLoader = new AsyncTaskCounter(this);
asyncTaskLoader.forceLoad();
return asyncTaskLoader;
}
@Override
public void onLoadFinished(Loader<Void> arg0, Void arg1) {
}
@Override
public void onLoaderReset(Loader<Void> arg0) {
}
}
这篇关于从AsyncTaskLoader更新进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!