In my current project i was ask to: if a user wants to cancel, lets say a web service from retrieving information (sometimes these are heavy operations, and take some time and the user may not want to wait), the only thing he would need to do was to tap the “Back” button. Although is pretty simple to just set a progressDialog “cancelable” (when you click the “Back” button the progressDialog will disappear), if you want to, for example, stop a thread that is running while the progressDialog is showing, you need to make something else:
1:
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(this);
With this, you are saying that the progressDialog can be canceled, and also you are going to create a Listener for the “cancel action”. Note that we are going to use our activity as the listener (note the “this” inside the ()).
2. We are you going to add an implementation to our activity, so its able to listen to that kind of actions:
public class YourClass extends Activity implements OnCancelListener
3. Finally we override this method (note you may get an error when you implement OnCancelListener, but you can resolve it, by adding the method onCancel):
@Override
public void onCancel(DialogInterface arg0) {
//your code goes here.
}
4. So when you press the “Back” button, the onCancel method will trigger and you can stop/cancel/save anything that you want along with the dismiss of the progressDialog.
Hope it helps.


