I've done a lot of reading on the subject without finding the correct solution.
I have a program which does a network discovery (using ping). I don't understand how you stop the async task. I am doing a task.cancelled(true) but it seems to do nothing. On top of it I'm doing a while() to check if the task is cancelled which returns true immediately.
The sequence: is start (works fine) I wait 5-10 IP addresses and I click on the button stop. Then I click on start but the discover task is not executed.
Can we really stop an async task? How? What is the delay for it?
EDIT
I'm lost. All the Qs in Stackoverflow state that the cancel(true) needs to come from in the task.
I have an example where I called the cancel(true) inside the doinbackground but it didn't trigger the onCancelled
Most of the case (at least for loops) the stop must come outside the task. My example below simply plays on the loop counter. That works.
One interisting comment came from wrygiel in the Q Ideal way to cancel an executing AsyncTask
it would be great to have a real example.
Here is my code modified but the onCancelled didn't work so I play on the loop counter.
public class MainActivity extends AppCompatActivity {
TextView text;
Discover discover;
int count;
private boolean running = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button) findViewById(R.id.start);
Button stop = (Button) findViewById(R.id.stop);
text = (TextView) findViewById(R.id.txt);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
discover = new Discover();
discover.execute();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// if(discover != null)
// discover.cancel(true);
count = 255;
}
});
}
private class Discover extends AsyncTask<Object, String, Void> {
@Override
protected Void doInBackground(Object... params) {
String ip;
Ping ping = new Ping();
for(count=1;count<255;count++) {
if(!running) {
count = 255;
Log.i("Discover", "task terminated");
}
ip = "192.168.1." + count;
if (!ping.pong(ip))
publishProgress(ip+" not alive ");
else
publishProgress(ip+" is alive");
}
return null;
}
@Override
protected void onPreExecute() {
text.setText("Start search...");
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
text.setText(values[0]);
}
@Override
protected void onPostExecute(Void result) {
text.setText("Task finished");
super.onPostExecute(result);
}
@Override
protected void onCancelled() {
running = false;
super.onCancelled();
}
}
}