I have a small code where I read a serialized file of 100 items in doInBackground, create a ArrayList and return from doInBackground. In PostExecute, I just copy the array list to my another ArrayList object which is tied to ListView adapter.
With this I was getting cpu usage 10-40% with a 10s timer.
I removed the async task and did doInackgrounf and postExecute work in ui thread serially, and I am always < 5% cpu in top command output.
SO is AsyncTask cpu hungry ?
Update below is code in myAsyncTask
class MyAsyncTask extends AsyncTask<String, String, ArrayList<Info>> {
@Override
protected ArrayList<Info> doInBackground(String... params) {
ArrayList<Info> arr_list = new ArrayList<Info>() {
};
try {
File f = new File(mainApp.getFilesDir(), "");
String[] paths = f.list();
ArrayList<String> delfiles = new ArrayList<String>() {
};
long n = 0;
if (paths == null)
return arr_list;
for (int i = 0; i < paths.length; i++) {
try {
long fname = Long.valueOf(paths[i]);
if (fname > n)
n = fname;
delfiles.add(paths[i]);
} catch (Exception e) {
continue;
}
}
lastFileNum = n;
if (n > 0) {
File fp = new File(mainApp.getFilesDir(), String.valueOf(n));
FileInputStream fos = new FileInputStream(fp);
ObjectInputStream os;
os = new ObjectInputStream(fos);
int count = (Integer) os.readObject();
for (int i = 0; i < count; i++) {
Info ai = (Info) os.readObject();
arr_list.add(ai);
}
os.close();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr_list;
}
@Override
protected void onPostExecute(ArrayList<Info> arr_list) {
try{
if (this.isCancelled()) {
return;
}
if (arr_list != null && arr_list.size() > 0) {
if (this.isCancelled()) {
return;
}
mainApp.Info_data.clear();
for (int i = 0; i < arr_list.size(); i++) {
mainApp.Info_data.add(arr_list.get(i));
}
if (this.isCancelled()) {
return;
}
if (this.isCancelled()) {
return;
}
adapter.notifyDataSetChanged();
}
if (this.isCancelled()) {
return;
}
}
catch(Exception e){
}
}
}
And called using matk.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, str);