Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Android App Auto-Update with Retrofit2 and RxJava2

Tech 2

App auto-update functionality typically involves three core tasks: downloading the APK file, displaying real-time download progress, and triggering installation upon completion. The most challenging aspect is elegantly updating the UI with download progress—especially within background services. This implementation leverages Retrofit2 and RxJava2, using OkHttp’s interceptor mechanism to monitor byte-level download progress and propagate updates via a custom event bus.

The solution hinges on wrapping the HTTP response body to intercept read operations. A custom ResponseBody subclass tracks cumulative bytes read and emits progress events through an RxBus built with RxJava’s PublishSubject. These events are consumed in a background IntentService, which updates a persistent notification with the current download percentage.

Key Components

  • ApiManager: Configures Retrofit with a custom OkHttp client that injects a progress-tracking enterceptor.
  • ApkLoadingBean: Holds total file size and downloaded bytes.
  • ApkResponseBody: Overrides source() to wrap the original response stream and emit progress events during reads.
  • RxBus: A lightweight event dispatcher using RxJava for decoupled communication.
  • UpdateApkService: Background service that initiates the download, subscribes to progress events, and manages the notification.
  • UpdateHelper & UpdateManager: Coordinate update checks, user prompts, and download initiation.

Progress Tracking via Interceptor

The OkHttp interceptor replaces the original response body with ApkResponseBody:

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(chain -> {
        Response response = chain.proceed(chain.request());
        return response.newBuilder()
            .body(new ApkResponseBody(response))
            .build();
    })
    .build();

Inside ApkResponseBody#source(), each read operation updates a counter and posts progress:

@Override
public BufferedSource source() {
    return Okio.buffer(new ForwardingSource(originalResponse.body().source()) {
        long bytesReadTotal = 0L;

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long bytesRead = super.read(sink, byteCount);
            bytesReadTotal += (bytesRead != -1) ? bytesRead : 0;
            RxBus.getDefault().post(new ApkLoadingBean(
                originalResponse.body().contentLength(),
                bytesReadTotal
            ));
            return bytesRead;
        }
    });
}

Event Handling in Service

The UpdateApkService subscribes to ApkLoadingBean events and updates the notification:

private void observeDownloadProgress() {
    Disposable disposable = RxBus.getDefault()
        .toObservable(ApkLoadingBean.class)
        .subscribe(bean -> {
            int percent = (int) ((double) bean.downloaded / bean.total * 100);
            notificationBuilder.setProgress(100, percent, false);
            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
            if (percent == 100) {
                notificationManager.cancel(NOTIFICATION_ID);
            }
        });
    compositeDisposable.add(disposable);
}

This architecture cleanly separates network logic, progress monitoring, and UI updates, enabling a responsive and maintainable auto-update flow.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.