Oliver Dixon
Oliver Dixon

Reputation: 7405

Cancelling a service from a notification button

I'm trying to cancel an upload service from my progress notification using the 'cancel' button.

But I cannot get this working.

Notification is created

//Intent class changes from first activity then to service when it's uploading.
Intent cancel = new Intent(intentClass, BaseUploadService.class);
PendingIntent cancelUploadIntent = PendingIntent.getBroadcast(intentClass, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder
.setSmallIcon(R.drawable.notificationicon)
.setContentTitle(title)
.setContentText(filename)
.setAutoCancel(totalAmount > uploadedAmount)
.setProgress((int) totalAmount, (int) uploadedAmount, false)
.addAction(R.string.assignment_icon_group, intentClass.getString(R.string.cancel), cancelUploadIntent)
;
return builder.build();

Listen for intent from notification button.

public class BaseUploadService extends IntentService {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.debug("onStartCommand - BaseUploadService");
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }

    public BaseUploadService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }
}

Nothing is ever received in the service. + there could be multiple services.

Upvotes: 1

Views: 812

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38299

Change PendingIntent.getBroadcast() to PendingIntent.getService().

If after that change the service is still not started, try building the notification with setContentIntent instead of addAction.

Check your manifest to confirm that BaseUploadService is declared correctly.

Upvotes: 2

Related Questions