gpt4 book ai didi

android - 从 AsyncTaskLoader 更新进度条?

转载 作者:IT老高 更新时间:2023-10-28 23:33:59 25 4
gpt4 key购买 nike

当使用 AsyncTaskLoader 时,您将如何更新显示状态的进度条,因为它正在被更新?通常你会等待回调在完成后移除,但是如何运行更新呢?您会让主线程 (ui) 在设置数据时轮询数据吗?

编辑:我说的是AsyncTaskLoader,看看加载器部分。这是类(class)链接:http://developer.android.com/reference/android/content/AsyncTaskLoader.html

我想使用它,因为它是 future :),我知道如何使用 AsyncTask 来做到这一点。

最佳答案

您可以使用加载器来做到这一点,但您需要在您的 Activity 上保留和更新 WeakReference:

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) {

}

}

关于android - 从 AsyncTaskLoader 更新进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9077212/

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