Issue
I'm working in an Android application that is using Microsoft Azure Face Api to get some information from an image. After analizing all the people in the image I get the results in the postExecute() call correctly, but now I need to do some changes if I detect an specific person (all the work is different if this specific person is detected).
I correctly detect this person but I want to know if I can do my work in the DoInBackground() so that I don't need to wait for the result (because if I detected this person I need to send a socket message and the result is not valid).
I actually receive a full list of people in the onResult, then I look through all this list to find the specific person and send the socket message. I want to know if I can send this message as soon as I detect this person in the DoInBackground() and cancel the rest of the execution.
Solution
Considering the official documentation :
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(java.lang.Object), instead of onPostExecute(java.lang.Object) will be invoked after doInBackground(java.lang.Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(java.lang.Object[]), if possible (inside a loop for instance.)
So if you want to stop the task you can do something like:
class myAsyncTaskClass(val pictures:List<Pictures>, Void, Boolean){
fun doInBackground(var args){
// Check all your pictures, if you find the right face stop your task
if (specificPersonIsDectected){
cancel()
return specificPersonIsDectected
}
}
fun onCancelled(var specificPersonIsDectected){
//Notify you found the specific person
}
}
I encourage you to read the official documentation to understand how you should work with AsyncTask
Answered By - Robert LaFondue
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.