I’m working on an Android app that uploads files to Google Drive using background tasks. While I can cancel the background task itself, I’m struggling to figure out how to actually stop the upload process that’s already in progress.
Once the execute() method starts running, the file keeps uploading even if I try to cancel the task. Is there a way to interrupt the actual upload operation? I need to give users the ability to stop uploads that are taking too long or when they change their mind. Any suggestions on how to properly handle this would be really helpful.
Hit this same issue last year building a backup app. You can’t just cancel at the task level - you need to kill the actual HTTP request. I fixed it by creating a custom HttpRequestInitializer that sets timeouts and can abort the connection. Set up an HttpTransport with configurable timeouts, then use HttpRequest.setInterceptor() to check cancellation flags during upload. Another trick that worked: wrap the whole upload in its own thread and keep a reference so you can interrupt it when needed. Google Drive API usually respects thread interruption, but your cancellation logic has to actually reach the network layer. Otherwise the upload keeps eating bandwidth even though your UI says it’s canceled.
The issue with execute() is that it blocks and cannot be canceled once initiated. A better approach would be to utilize executeAsync(), or refactor your upload logic to allow interruptions. In a similar situation while developing a document management app, I found success with HttpRequestExecutor combined with a custom HttpRequestInitializer that actively monitors cancellation status. Another option is to encapsulate the upload call within a Future using ExecutorService.submit(), which allows invoking future.cancel(true) to halt the process. Keep in mind though, that this won’t immediately terminate active network operations. For an improved user experience, consider implementing chunked uploads by utilizing setChunkSize() on your media content, allowing for natural pause points in the upload process.
Ugh, been there! execute() is basically a black hole once it starts. I switched to executeMediaAndDownloadTo() with a custom OutputStream that checks for cancellation flags. Override the write() method to throw an exception when you need to cancel. Not pretty, but it actually stops uploads mid-stream unlike other methods.