【发布时间】:2020-07-31 17:38:12
【问题描述】:
我想要一个方法(在 MainActivity 中)从 MyAsynctask 类(在 MainActivity 中)的 doInBackground(File... file) 方法中调用,并且该方法必须在后台工作,因为它需要时间并且我的应用程序会暂时停止工作并且没有出现我在onPreExecute() 方法中调用的任何对话框如何解决这里的问题是我的代码它工作得很好但花费了太多时间而且我的应用程序看起来挂起但实际上并非如此。
ArrayList<HashMap<String,String>> getPlayList(File rootFolder) {
ArrayList<HashMap<String,String>> fileList = new ArrayList<>();
try {
File[] files = rootFolder.listFiles();
//here you will get NPE if directory doesn't contains any file,handle it like this.
if (files != null) {
for (File file : files) {
if (file.isDirectory() && !file.isHidden()) {
if (true) {
fileList.addAll(getPlayList(file));
}
else {
break;
}
} else if (file.getName().endsWith(".pdf")) {
HashMap<String, String> song = new HashMap<>();
song.put("file_path", file.getAbsolutePath());
song.put("file_name", file.getName());
fileList.add(song);
}
}
}
return fileList;
} catch (Exception e) {
return null;
}
}
Asynctask 类在下面..
private class AsyncTaskExample extends AsyncTask<File, String, ArrayList> {
@Override
protected ArrayList doInBackground(File... file) {
ArrayList<HashMap<String,String>> songList=getPlayList(folder);
if(songList!=null){
for(int i=0;i<songList.size();i++){
final String fileName=songList.get(i).get("file_name");
final String filePath=songList.get(i).get("file_path");
//saving filePath and filName in SQLite Database..
saveFileToDatabase(filePath, fileName);
}
}
return songList;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setMessage("Please wait...Loading..");
p.setIndeterminate(false);
p.setCancelable(false);
p.show();
}
@Override
protected void onPostExecute(ArrayList arrayList) {
super.onPostExecute(arrayList);
if (mFiles != null)
{
p.dismiss();
}
else
{
p.show();
}
}
}
如何高效地完成工作?
解决方案
问题在于下面给出的这些代码行:
AsyncTaskExample taskExample = new AsyncTaskExample();
folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
//I was writing this below line..
taskExample.doInBackground(folder);
//but it should be like in line below..
taskExample.execute(folder);
【问题讨论】:
-
如果可以将 AsyncTask 替换为另一个选项(可观察、协程),那将是最明智的选择。
标签: java android arraylist android-asynctask background