According to our research, there are misuses about the following servral AsyncTask classes:
( in ru.valle.btc. MainActivity.java)
@Nullable
private AsyncTask<Void, Void, KeyPair> addressGenerateTask;
@Nullable
private AsyncTask<Void, Void, GenerateTransactionResult> generateTransactionTask;
@Nullable
private AsyncTask<Void, Void, KeyPair> switchingCompressionTypeTask;
@Nullable
private AsyncTask<Void, Void, KeyPair> switchingSegwitTask;
@Nullable
private AsyncTask<Void, Void, KeyPair> decodePrivateKeyTask;
@Nullable
private AsyncTask<Void, Void, Object> bip38Task;
@Nullable
private AsyncTask<Void, Void, ArrayList<UnspentOutputInfo>> decodeUnspentOutputsInfoTask;
The problems are:
- They are anonymous inner classes. They hold strong reference to the GUI element of Activity( MainActivity ), which can lead to memory leak when the Activity is destroyed and the AsyncTask did not finish
- Their instances are cancelled before the Activity is destroyed. But in the doInBackground method there are for or while loop without the call of isCancelled() . These loops may not be able to terminate when the task is cancelled. This will cause waste of resources or even flashback
I think we can make following changes to fix the misuse problems:
- I think the GUI-related fields should be wrapped into WeakReference. Take
private final MainActivity _context as example, it can be changed to private final WeakReference<MainActivity> _context.
- Every loop should check the status of AsyncTask to break the loop.
while(condition1){
if(isCancelled()){
break;
}
//blablabla…
while(condition2){
if(isCancelled()){
break;
}
//blablabla…
}
}
These are my suggestions above, thank you.
According to our research, there are misuses about the following servral AsyncTask classes:
( in ru.valle.btc. MainActivity.java)
The problems are:
I think we can make following changes to fix the misuse problems:
private final MainActivity _contextas example, it can be changed toprivate final WeakReference<MainActivity> _context.These are my suggestions above, thank you.