DEV Community

Cover image for ussd_session: send USSD balance codes from Flutter with the official Android API
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

ussd_session: send USSD balance codes from Flutter with the official Android API

USSD codes are the short strings you dial to ask the network something: *222# for a balance, another code for a data bundle or an account query. On prepaid lines they are often the only way to get that information. So an app that wants to show "your balance on SIM 1 and SIM 2" has to send a USSD code and read the reply.

On Android this is a narrow door. There is exactly one public API for it, TelephonyManager.sendUssdRequest, which sends one string and delivers one reply to a callback. Around that call there are many ways to fail: no permission, no SIM, an old Android version, a second SIM the device ignores, a network that never answers. Some approaches go around the API with an AccessibilityService that reads the system USSD dialog, and that is fragile and raises Play policy problems.

ussd_session is a Flutter plugin that stays inside the official API. It sends single-response USSD requests, targets a specific SIM, turns every failure into a typed error, and offers a dialer fallback for everything the API cannot do. It is Android only: send needs API 26 or later, and dial works on any Android version. iOS is not supported.

What it does

Sending. UssdSession.send(code, subscriptionId:, timeout:) calls TelephonyManager.sendUssdRequest and returns a UssdResponse with the request, the reply text, the subscription id and the time it was received.

Dual SIM. UssdSession.simCards() lists the active SIMs from SubscriptionManager.getActiveSubscriptionInfoList, with subscription id, slot, carrier name, display name, MCC/MNC and country ISO. send then targets a SIM through TelephonyManager.createForSubscriptionId.

Typed failures. Every error is a UssdException with a UssdErrorCode, so you can tell a missing permission from a timeout from an unsupported device.

Permission status. UssdSession.permissionsStatus() reports CALL_PHONE and READ_PHONE_STATE without ever prompting.

A dialer fallback. UssdSession.dial(code) opens the dialer with the code filled in (ACTION_DIAL, with # encoded as %23). It needs no permission, and the user presses call.

Pure Dart helpers. UssdCode.validate, normalize and telUri check and clean codes. extractAmounts reads dinar amounts such as "150,00 DA", "150.00 DZD" or "١٥٠ دج" out of a reply.

Carrier presets. AlgerianCarrierPresets holds the Mobilis, Djezzy and Ooredoo balance codes, each checked on the carrier's own website.

How to use it

Add it from GitHub:

dependencies:
  ussd_session:
    git: https://github.com/AbdeldjalilChougui/ussd_session
Enter fullscreen mode Exit fullscreen mode

Declare the permissions you use in android/app/src/main/AndroidManifest.xml. The plugin does not declare them for you, so an app that only uses dial does not ask for phone permissions:

<!-- Needed by UssdSession.send -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!-- Needed by UssdSession.simCards (and for checking a subscriptionId before sending) -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Enter fullscreen mode Exit fullscreen mode

send needs Android 8.0 (API 26) and CALL_PHONE. simCards needs Android 5.1 (API 22) and READ_PHONE_STATE. permissionsStatus and dial work on any version with no permission.

The plugin only reports the permission status. Request at runtime with a package such as permission_handler, whose Permission.phone asks for the phone permission group on Android:

Future<bool> ensureUssdPermissions() async {
  final status = await UssdSession.permissionsStatus();
  if (status.canSend && status.canListSims) return true;
  return (await Permission.phone.request()).isGranted;
}
Enter fullscreen mode Exit fullscreen mode

Then send a balance code on each SIM:

import 'package:ussd_session/ussd_session.dart';

Future<void> checkBalances() async {
  final sims = await UssdSession.simCards();
  for (final sim in sims) {
    final preset = AlgerianCarrierPresets.balanceFor(sim);
    if (preset == null) continue;
    try {
      final reply = await UssdSession.send(
        preset.code,
        subscriptionId: sim.subscriptionId,
        timeout: const Duration(seconds: 20),
      );
      print('${sim.carrierName}: ${reply.text}');
      print('Amounts found: ${extractAmounts(reply.text)}');
    } on UssdException catch (e) {
      switch (e.code) {
        case UssdErrorCode.unsupported:
          await UssdSession.dial(preset.code); // Android < 8: let the user dial
        case UssdErrorCode.callPhonePermissionDenied:
          print('Grant the phone permission first');
        default:
          print('USSD failed: ${e.code.name} (${e.message})');
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The same call works for any carrier's single-response code, for example UssdSession.send('*123#') on the default SIM.

The error codes are invalidCode (checked in Dart before any platform call), returnFailure, serviceUnavailable (no service, airplane mode, another USSD session in progress), callPhonePermissionDenied, readPhoneStatePermissionDenied, noSim, invalidSubscription, timeout (30 s by default), unsupported (Android below 8.0, no telephony hardware, or not running on Android), noDialer and unknown.

The helpers work without a device:

UssdCode.validate(' *222 # ');   // '*222#' (spaces removed)
UssdCode.validate('*٢٢٢#');     // '*222#' (Arabic-Indic digits converted)
UssdCode.isValid('*22a#');      // false
UssdCode.telUri('*222#');       // 'tel:*222%23'

extractAmounts('Votre solde est de 1 250,50 DA'); // [1250.5]
extractAmounts('رصيدك الحالي هو ١٥٠ دج');           // [150.0]
Enter fullscreen mode Exit fullscreen mode

extractAmounts is a heuristic. Carriers do not standardise their messages and change them without notice. It understands DA, DZD, دج and د.ج before or after the number, ASCII and Arabic-Indic digits, and thousands grouped with spaces, dots or commas. It reads "1.250 DA" as 1250, and two numbers separated only by a space before a currency may be read as one grouped number.

Things to know

  • Single-response USSD only. Multi-step menus are not supported. There is no official API to answer a menu ("1. Balance 2. Bundles") and keep the session open. The only ways to do that are an AccessibilityService that reads and types into the system USSD dialog, or private telephony internals. Both are deliberately left out. If a code answers with a menu, you get the first screen's text and the session ends. For such codes, use dial and let the user navigate. Some carriers let you put the menu choices in the code itself (for example *123*1*2#); only use that form if your carrier documents it.
  • One request at a time. Wait for each reply before sending the next one. While a request is pending, Android fails a new one at once with returnFailure.
  • A timeout does not cancel the request. Android has no API for it. If the network never answers, the request stays pending in the phone process, even after the app exits, and every later send fails with returnFailure until the radio turns off (airplane mode) or the device restarts. The API 37 emulator's modem behaves this way: it accepts *100# and never replies.
  • Some devices ignore the chosen SIM. Some devices and carriers ignore the subscription chosen with createForSubscriptionId and use the default SIM. The plugin cannot detect this.
  • MNC on old Android. Below Android 10, the platform gives the MNC as a number. A leading zero is restored for one-digit values (Algerian MNCs are 01, 02, 03), but a three-digit MNC with a leading zero cannot be recovered.
  • The presets can go stale. The three codes were read on the carriers' own websites on 2026-09-26: *222# for Mobilis, *710# for Djezzy (prepaid lines) and *200# for Ooredoo. Carriers can change these codes at any time, and a code may answer with a menu rather than a single message.
  • What was tested. The Kotlin pure logic has JUnit tests. The example app has an emulator integration test that checks the permission errors, invalid codes, simCards() against the emulator SIM, send with and without a subscription id (timeout, then returnFailure while that request is pending, invalidSubscription), and that dial opens the dialer showing *100#. It was tested on the Android Emulator (Pixel 10 image, API 37).
  • What was not tested. A real network reply, dual-SIM devices, Android below 10, and any physical phone. The response texts in the tests were written for the tests and are not copies of operator messages.

Why I built it

The README draws a clear line, and the line is the reason for the package. USSD on Android has one official call. A plugin can either wrap that call honestly, or go around it by reading other apps' windows. This one never reads or types into other apps' windows and does not use an AccessibilityService.

Inside that line, what was missing was the rest of the job: choosing the SIM, checking the code before it reaches the platform, knowing why a request failed, and having a fallback that always works. dial is that fallback. It asks for no permission and hands the code to the user. I also wanted the limits written down in plain words, including the unpleasant one about requests that time out and stay pending, because that is the kind of behaviour you only find after shipping.

Get the code

The source, the error table, the data sources for the presets and the tests are on GitHub: https://github.com/AbdeldjalilChougui/ussd_session. It is MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)