I searched a lot but I can't figure how to stop IntentService
on button click. I have a button that starts IntentService
then progressDialog
shows Via ResultReceiver
I get data back. This app searches and display photos from the device, so I think IntentService
is the right way to do it. But I want to stop it on Cancel button. Is there some example or good practice of this?
MainAcitivity
:
@Override
public final void onReceiveResult(final int resultCode, final Bundle resultData) {
switch (resultCode) {
case ScanService.STATUS_RUNNING:
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//something to stop
}
});
progressDialog.show();
break;
case ScanService.STATUS_FINISHED:
progressDialog.dismiss();
listOfPictures = resultData.getParcelableArrayList(DATA_KEY);
break;
case ScanService.STATUS_ERROR:
final String error = resultData.getString(Intent.EXTRA_TEXT);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
break;
}
}
ScanService:
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
protected void onHandleIntent(final Intent intent) {
final ResultReceiver scanResultReceiver = intent.getParcelableExtra(RECEIVER_KEY);
final Bundle bundle = new Bundle();
scanResultReceiver.send(STATUS_RUNNING, bundle);
// some work here
bundle.putParcelableArrayList(DATA_KEY, new ArrayList<>(listOfPictures));
scanResultReceiver.send(STATUS_FINISHED, bundle);
}