gpt4 book ai didi

android - 静态异步任务进度条

转载 作者:行者123 更新时间:2023-11-29 01:04:46 25 4
gpt4 key购买 nike

抱歉,如果这看起来是一个基本问题。我已经更新了 Android Studio 并注意到我的 AsyncTasks 上有一些内存泄漏警告说我应该将它们设为静态。我已将它们设为静态,但似乎无法在没有收到相同内存泄漏警告的情况下使 List、ProgressBar、ImageView 之类的东西正常工作。看来我怎么试都赢不了。我想我的问题是:

  1. AsyncTasks 应该是静态的吗?官方文档并未将其设为静态,但我的 IDE 会发出警告说他们应该这样做。

  2. 如果它们是静态的,我如何在静态 AsyncTask 中启动和停止 ProgressBar。

编辑

这仍然会抛出“This AsyncTask class should be static or leaks might occur”

private class DownloadCategoryTask extends AsyncTask<String, Integer, String> {

@Override
protected String doInBackground(String... params) {

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

String url = Config.API_URL +
"/Index.aspx?" +
"type=3&" +
"site_id=" + SITE_ID;

String method = "GET";

String array_name = "categories";

Downloaded_category_array = Config.getJSONNew(url, method, array_name, context);

return "";

}

protected void onPostExecute(String result) {

if(isCancelled()){
return;
}

getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//Update your UI here
//showProgressBar();
}
});

Populate_category_list();
}
}

最佳答案

试试我发现的这个解决方案:

public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

progressBar = findViewById(R.id.progress_bar);
}

public void startAsyncTask(View v) {
ExampleAsyncTask task = new ExampleAsyncTask(this);
task.execute(10);
}

private static class ExampleAsyncTask extends AsyncTask<Integer, Integer, String> {
private WeakReference<MainActivity> activityWeakReference;

ExampleAsyncTask(MainActivity activity) {
activityWeakReference = new WeakReference<MainActivity>(activity);
}

@Override
protected void onPreExecute() {
super.onPreExecute();

MainActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}

activity.progressBar.setVisibility(View.VISIBLE);
}

@Override
protected String doInBackground(Integer... integers) {
for (int i = 0; i < integers[0]; i++) {
publishProgress((i * 100) / integers[0]);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Finished!";
}
}
}

引用:here

关于android - 静态异步任务进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48079850/

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