Skip to main content

telephony_kit 0.5.0 copy "telephony_kit: ^0.5.0" to clipboard
telephony_kit: ^0.5.0 copied to clipboard

Phone calls, dialer role, in-call control, SIM, network and call log APIs for Flutter on Android, using JNI bindings generated by jnigen. No method channels.

telephony_kit #

pub package CI License: MIT

Build a complete phone app in Flutter on Android: place and control calls, become the default dialer with your own in-call screen, block and screen calls, search the call log and contacts, read SIM and live network info, run USSD codes and send SMS.

  • No method channels. Every API is a direct JNI call through bindings generated by jnigen, so it is fast, synchronous where Android is, and fully typed.
  • A real dialer, not just tel: links. Incoming call notifications that show over the lock screen, answer and decline, hold, keypad tones, mute, speaker and Bluetooth, swap and conference calls.
  • Call blocking that works when your app is closed. Block numbers, prefixes, unknown or hidden callers, plus the system block list.
  • Ready for AI agents. Ships an agent skill and AGENTS.md so coding assistants use it correctly.
Keypad Incoming call In call Recents
Keypad Incoming call In-call controls Recent calls

Features #

Feature Needs
Open the system dialer with a number nothing
Place a call, choose the SIM, call voicemail CALL_PHONE
Network, SIM and phone details, live signal and 2G to 5G events READ_PHONE_STATE for some details
Call log and call log search READ_CALL_LOG
Delete call log entries, mark missed calls seen WRITE_CALL_LOG
Contact search, caller lookup by number, every detail of a contact READ_CONTACTS
Add, edit, delete contacts and favorites WRITE_CONTACTS
USSD codes such as *100# CALL_PHONE, Android 8.0+
Send SMS / search SMS SEND_SMS / READ_SMS
Default dialer and call screening roles nothing
Call events, answer, reject (with a text), hang up, hold, DTMF, mute, audio routes and Bluetooth, swap, merge and conference, SIM choice, why a call ended, pause digits, proximity screen off, call and missed call notifications the app is the default dialer and declares the in-call service
Emergency number check nothing
Call screening with block rules default dialer or call screening role, and the screening service declared
System block list the app is the default dialer

Android only (API 24+). iOS does not let third-party apps replace the phone app or read call data, so it is not supported; on other platforms the APIs throw.

Install #

dependencies:
  telephony_kit: ^0.5.0

Minimum Android version is API 24 (Android 7.0).

Quick start #

import 'package:telephony_kit/telephony_kit.dart';

final telephony = TelephonyKit.instance;

// Open the dialer (no permission needed).
telephony.openDialer('+201234567890');

// Place a call directly (needs CALL_PHONE).
if (telephony.hasPermission(TelephonyPermission.callPhone)) {
  telephony.placeCall('+201234567890');
}

// Device and network.
final info = telephony.getNetworkInfo();
print('${info.networkOperatorName}, roaming: ${info.isRoaming}');
for (final sim in telephony.getSimCards()) {
  print(sim);
}

// Call log (needs READ_CALL_LOG).
for (final entry in telephony.getCallLog(limit: 20)) {
  print(entry);
}
// Call log: by name or number, call type and date. Runs in Android's
// provider, so only matching rows reach Dart.
final missedToday = telephony.searchCallLog(
  query: '0100',            // also matches +20100...
  types: {CallLogType.missed},
  from: DateTime.now().subtract(const Duration(days: 1)),
);

// Contacts with a phone number, by name or number (needs READ_CONTACTS).
for (final contact in telephony.searchContacts('ahm')) {
  print('${contact.displayName}: ${contact.phones}');
}

// Who is calling?
final caller = telephony.lookupNumber('+201001234567');
print(caller?.displayName ?? 'Unknown');

An empty query to searchContacts lists all contacts that have a number, favorites first. Queries run synchronously on the calling isolate, which is fast for normal address books; use limit to keep results small.

Errors from Android, such as a missing permission, are thrown as TelephonyException.

Contacts: read, add, edit and delete #

searchContacts is a quick phone picker. For everything saved on a contact, use getContacts and getContact, which return ContactDetails (name parts, all phones, emails, addresses, company and job title, nickname, websites, note, birthday, photo and favorite):

// All contacts with every detail, even those without a number.
// A query matches the name, an email, or a phone number in any format.
final all = telephony.getContacts(limit: 500);
final sara = telephony.getContacts(query: 'sara').first;
final same = telephony.getContact(sara.id); // null if it was deleted

// Add. Returns the new contact id.
final id = telephony.addContact(
  const ContactDetails(
    givenName: 'Sara',
    familyName: 'Ali',
    phones: [ContactPhone(number: '+20 100 123 4567', label: 'Mobile')],
    emails: [ContactEmail(address: 'sara@example.com', label: 'Work')],
    company: 'Acme',
    birthday: '1990-05-04',
  ),
);

// Edit: read, change with copyWith, save. Returns false if it was deleted.
final edited = telephony.getContact(id)!.copyWith(
  jobTitle: 'CTO',
  phones: [
    ...telephony.getContact(id)!.phones,
    const ContactPhone(number: '0222345678', label: 'Work'),
  ],
);
telephony.updateContact(edited);

telephony.setContactStarred(id, true); // favorite
telephony.deleteContact(id);           // cannot be undone
telephony.deleteContacts([id1, id2]);  // returns how many were deleted

Reading needs READ_CONTACTS; adding, editing, favoriting and deleting need WRITE_CONTACTS. updateContact replaces the name, phones, emails, addresses, company, nickname, websites, note and birthday with what you pass, and leaves photos, groups and other data alone. addContact accepts accountType and accountName to save into a synced account such as Google. Contacts in a synced account are removed from the account when it next syncs. Labels such as Mobile, Home and Work map to Android's types; any other text becomes a custom label.

Permissions #

telephony_kit checks permissions but does not request them, because asking needs an activity result callback. Request them with a package such as permission_handler, and declare the ones you use in android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- Only to add, edit or delete contacts -->
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

Building a dialer app #

To receive calls and show your own in-call screen, the app must be the default dialer. That needs three things.

1. An activity that handles DIAL. Add these intent filters to your main activity:

<intent-filter>
    <action android:name="android.intent.action.DIAL" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.DIAL" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="tel" />
</intent-filter>

Adding android:showWhenLocked="true" and android:turnScreenOn="true" to the activity lets the incoming call screen show over the lock screen.

Once the app is the default dialer, tapping a phone number anywhere (and openDialer) opens your activity with a tel: uri. Read it with takeDialNumber() when the app starts and resumes, and show it on your keypad. For that, turn off Flutter deep linking in the activity, or Flutter tries to open the number as a route:

<meta-data
    android:name="flutter_deeplinking_enabled"
    android:value="false" />

and keep the latest intent in MainActivity:

@Override
protected void onNewIntent(@NonNull Intent intent) {
  super.onNewIntent(intent);
  setIntent(intent);
}

2. The in-call service. Declare the service that ships with the package inside <application>:

<service
    android:name="dev.telephonykit.telephony_kit.TelephonyKitInCallService"
    android:permission="android.permission.BIND_INCALL_SERVICE"
    android:exported="true">
    <meta-data
        android:name="android.telecom.IN_CALL_SERVICE_UI"
        android:value="true" />
    <!-- false lets the system play the ringtone. -->
    <meta-data
        android:name="android.telecom.IN_CALL_SERVICE_RINGING"
        android:value="false" />
    <intent-filter>
        <action android:name="android.telecom.InCallService" />
    </intent-filter>
</service>

The package does not declare it for you, so apps that only use the other APIs are not registered as an in-call UI.

3. Ask the user for the role.

if (!telephony.isDefaultDialer) {
  telephony.requestDefaultDialer(); // Shows the system prompt.
}
// Check isDefaultDialer again when the app resumes.

Then listen for calls:

telephony.callEvents.listen((event) {
  switch (event) {
    case CallAdded(:final callId):
      final call = telephony.call(callId);
      print('${call.isIncoming ? 'Incoming' : 'Outgoing'}: ${call.number}');
    case CallStateChanged(:final callId, :final state):
      print('$callId is now $state');
    case CallDisconnected(:final callId, :final cause):
      print('$callId ended: ${cause.displayText}');   // "Busy", "Call failed" ...
    case CallRemoved(:final callId):
      print('$callId removed');
    case PostDialWait(:final callId, :final remaining):
      telephony.call(callId).continuePostDial(true); // send "$remaining"
    case AudioStateChanged(:final muted, :final route):
      print('muted: $muted, route: $route');
  }
});

final call = telephony.calls.first;
call.answer();      // or reject(), hangUp(), hold(), unhold()
call.playDtmf('5');
call.stopDtmf();
telephony.setMuted(true);
telephony.setSpeakerOn(true);

Call notifications #

While the app is the default dialer, telephony_kit shows:

  • an incoming call notification with Answer and Decline buttons. It opens your app full screen on the lock screen, and on Android 12+ it uses the system call style.
  • an ongoing call notification with a timer and a Hang up button.

Add these permissions so they can show:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />

On Android 13+ also request POST_NOTIFICATIONS at runtime. Turn them off with telephony.showCallNotifications = false if you build your own. When a call starts ringing the service also tries to open your launcher activity; turn that off with telephony.launchAppOnIncomingCall = false.

Choosing the SIM (dual SIM) #

When the phone has no default SIM for calls, an outgoing call waits in CallState.selectPhoneAccount until your app picks one:

if (call.state == CallState.selectPhoneAccount) {
  final options = call.selectablePhoneAccounts;   // PhoneAccount: id, label, slotIndex
  showPicker(options.map((a) => a.displayName));  // "SIM 1 · Vodafone"
  call.selectPhoneAccount(options.first.id, setDefault: false);
}
print(call.phoneAccount?.displayName);            // the SIM this call uses

getPhoneAccountDetails() lists every calling account with its label and slot, for your own SIM selector before dialing.

Rejecting with a message #

call.reject(message: "Can't talk now, I'll call you back.");
print(call.cannedTextResponses);  // the user's replies from phone settings
print(telephony.quickReplies);    // package defaults, which you can replace

Android sends the text itself, so no SMS permission is needed.

Why a call ended, pause digits and emergency numbers #

  • call.disconnectCause (also in the CallDisconnected event) has a code (DisconnectCode.busy, rejected, error ...), Android's label and description, displayText for the UI and isFailure. It stays readable for the last 20 calls.
  • A ; in a dialed number (for example 0223456789;1234) sends a PostDialWait event; answer with call.continuePostDial(true). A , pauses and continues by itself.
  • telephony.isEmergencyNumber('112') checks the local emergency list. Call screening never blocks or silences emergency numbers.

Proximity sensor #

During a call on the earpiece the package keeps a proximity wake lock, so the screen turns off near the ear and your cheek cannot press buttons. It is released on speaker, Bluetooth, while ringing and after the call. Turn it off with telephony.proximitySensorEnabled = false.

Missed call notifications #

As the default dialer, Android asks your app to show missed call notifications. Declare the receiver inside <application>:

<receiver
    android:name="dev.telephonykit.telephony_kit.TelephonyKitMissedCallReceiver"
    android:permission="android.permission.MODIFY_PHONE_STATE"
    android:exported="true">
    <intent-filter>
        <action android:name="android.telecom.action.SHOW_MISSED_CALLS_NOTIFICATION" />
    </intent-filter>
</receiver>

The MODIFY_PHONE_STATE permission means only the system phone service can trigger it. The notification shows the count and last caller with a Call back button. markMissedCallsRead() and clearMissedCallNotification() clear it, and missedCallNotificationsEnabled = false turns it off.

Several calls and conferences #

telephony.swapCalls();                 // call waiting: hold one, resume the other
final call = telephony.calls.first;
if (call.canMerge) call.merge();       // make a conference
for (final party in call.children) {   // parties in a conference
  print(party.number);
}
call.children.first.splitFromConference();

To add a call, place another call with placeCall while one is active.

Audio routes and Bluetooth #

print(telephony.supportedAudioRoutes);  // {earpiece, speaker, bluetooth}
telephony.setAudioRoute(AudioRoute.speaker);
for (final device in telephony.bluetoothDevices) {
  print('${device.name} active: ${device.isActive}');
}
telephony.selectBluetoothDevice(telephony.bluetoothDevices.first.address);

Bluetooth device names need BLUETOOTH_CONNECT on Android 12+.

Call screening and blocking #

telephony_kit has two block lists.

The app's rules, applied by TelephonyKitCallScreeningService. They are saved on the device and work even when the app is closed:

final rules = telephony.screening;
rules.blockNumber('+201001234567');       // matches 01001234567 too
rules.blockPrefix('0900');                 // premium numbers
rules.unknownCallerAction = ScreeningAction.silence; // needs READ_CONTACTS
rules.hiddenNumberAction = ScreeningAction.reject;
rules.blockedAction = ScreeningAction.reject;       // the default

telephony.screenedCalls.listen((c) => print('${c.number}: ${c.reason}'));

Declare the service in your manifest:

<service
    android:name="dev.telephonykit.telephony_kit.TelephonyKitCallScreeningService"
    android:permission="android.permission.BIND_SCREENING_SERVICE"
    android:exported="true">
    <intent-filter>
        <action android:name="android.telecom.CallScreeningService" />
    </intent-filter>
</service>

Android uses it when the app is the default dialer. Other apps can ask for the call screening role with requestCallScreeningRole() (Android 10+). Silencing needs Android 10+.

The system block list (BlockedNumberContract) is shared with the phone and the SMS app, but only the default dialer may change it:

if (telephony.canBlockNumbers) {
  telephony.blockNumber('+201001234567');
  print(telephony.getBlockedNumbers());
  telephony.unblockNumber('+201001234567');
}

Network, signal, voicemail and USSD #

telephony.networkEvents.listen((event) {
  switch (event) {
    case SignalStrengthChanged(:final level):   // 0 to 4
      print('signal $level');
    case NetworkTypeChanged():
      print(event.generation.label);           // 2G, 3G, 4G, 5G
    case ServiceStatusChanged(:final status):
      print(status);
    case DeviceCallStateChanged(:final state):  // needs READ_PHONE_STATE
      print(state);
  }
});

print(telephony.signalLevel);
print(telephony.voicemailNumber);
telephony.callVoicemail();

final reply = await telephony.sendUssd('*100#');           // balance
final reply2 = await telephony.sendUssd('*100#', subscriptionId: 2);

USSD codes that open a multi-step menu only return the first screen.

Call log changes #

final missed = telephony.searchCallLog(types: {CallLogType.missed});
telephony.deleteCallLogEntries(missed.map((e) => e.id));
telephony.deleteCallLogForNumber('01001234567');
telephony.markMissedCallsRead();   // clears the missed call badge

These need WRITE_CALL_LOG.

SMS #

final parts = await telephony.sendSms('+201001234567', 'Hello');
final found = telephony.searchSms(query: 'code', type: SmsType.inbox);

sendSms completes when every part was sent (not delivered). Google Play only allows SEND_SMS and READ_SMS for the default SMS app and a few listed exceptions, so leave them out unless your app qualifies.

Google Play policy #

Google Play only allows the call log, SMS and some phone permissions for apps whose core purpose is to be the default phone (or SMS) app, and it asks you to declare that in the Play Console. Only declare the permissions for the features you use. Read the SMS and Call Log permissions policy before you publish.

Example #

example/ is a small dialer with a keypad (with SIM choice), recent calls with search and a missed filter, contacts with search, device details, and an in-call screen with answer, reject, hang up, mute, speaker and hold.

cd example
flutter run

How it works #

Dart API (lib/src/telephony_kit_impl.dart)
   │  uses
   ▼
jnigen bindings (lib/src/bindings.g.dart)
   │  JNI
   ├──► Android framework: TelecomManager, TelephonyManager, RoleManager,
   │    SubscriptionManager, ContentResolver, CallLog ...
   └──► Package Java (android/src/main/java):
        CallManager ◄── TelephonyKitInCallService (bound by the system)
        CallScreening ◄── TelephonyKitCallScreeningService (bound by the system)
        CallNotifications, CallActionReceiver (notification buttons)
        NetworkMonitor, UssdHelper, SmsHelper
        CallEventListener, ScreeningListener, NetworkEventListener,
        ResultListener (implemented in Dart)

Android only talks to services, receivers and abstract callback classes that are real Java subclasses, which cannot be generated from Dart. Those are the only Java code: the in-call and screening services, the notification button receiver, and small helpers for callbacks Android only offers as abstract classes (USSD, telephony callbacks, SMS results). jnigen generates Dart bindings for the helpers, and Dart implements the listener interfaces directly. Everything else calls the Android framework from Dart.

Regenerating the bindings #

The bindings are checked in. To regenerate them after changing the Java code or the list of Android APIs in tool/jnigen.dart:

export ANDROID_SDK_ROOT=/path/to/android/sdk   # needs platforms/android-36 or 35
flutter pub get
dart run tool/jnigen.dart

tool/jnigen.dart keeps an allow list of the Android methods and fields the package uses, so the generated file stays small.

Using telephony_kit with AI coding agents #

The package ships agent instructions inside the published package:

  • skills/telephony-kit/SKILL.md is a skill for agents building apps with telephony_kit: setup checklist, API map, patterns and pitfalls, with manifest and API references.
  • AGENTS.md is for agents working on this repository: the jnigen-only rule, how to add Android APIs and regenerate bindings, and the checks to run.

To give Claude Code the skill in your app project, copy the folder into your project's .claude/skills/:

mkdir -p .claude/skills
cp -r "$(ls -d ~/.pub-cache/hosted/pub.dev/telephony_kit-* | sort -V | tail -1)/skills/telephony-kit" \
  .claude/skills/

Other agents can be pointed at the same SKILL.md file, for example from your project's AGENTS.md.

License #

MIT

5
likes
0
points
199
downloads

Publisher

unverified uploader

Weekly Downloads

Phone calls, dialer role, in-call control, SIM, network and call log APIs for Flutter on Android, using JNI bindings generated by jnigen. No method channels.

Repository (GitHub)
View/report issues

Topics

#telephony #dialer #phone #calls #jni

License

unknown (license)

Dependencies

flutter, jni, jni_flutter

More

Packages that depend on telephony_kit

Packages that implement telephony_kit