DEV Community

Cover image for system_intents: let other Android apps call your Flutter app as a camera or clock
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

system_intents: let other Android apps call your Flutter app as a camera or clock

On Android, when an app needs a photo it usually does not build a camera. It fires an IMAGE_CAPTURE intent with startActivityForResult, and whichever camera app the user picks takes the picture and hands it back. The same idea covers video (VIDEO_CAPTURE), alarms (SET_ALARM) and timers (SET_TIMER).

If you write a camera app or a clock app in Flutter, you want to be on the receiving end of those intents. That takes more than an intent filter. You have to read the request's extras, which come from another app and cannot be trusted. You have to write the photo into the URI the caller gave you, or return a thumbnail if it gave none. And you have to finish the activity with the right result code.

system_intents is a Flutter plugin for that job. It gives you typed requests in Dart and safe replies to startActivityForResult callers. It is Android only: iOS apps cannot register as the system camera or clock handler, so there is no equivalent to support.

What it does

Reading the intent. SystemIntents.initialIntent() returns the intent that launched the activity. SystemIntents.intents streams intents that arrive later through onNewIntent.

Typed requests. Requests arrive as a sealed SystemIntent type, so a Dart switch covers every case:

  • ImageCaptureRequest: outputUri and returnThumbnail.
  • VideoCaptureRequest: outputUri, durationLimit, sizeLimit and quality.
  • SetAlarmRequest: hour, minutes, days, message, skipUi, vibrate and ringtone. days holds DateTime weekday numbers converted from Android's Calendar constants.
  • SetTimerRequest: lengthSeconds, message and skipUi.
  • ShowAlarmsRequest, ShowTimersRequest, DismissAlarmRequest and SnoozeAlarmRequest.
  • UnknownIntent: the action, data and primitive extras only.

Replying to capture requests. respondWithImage(path) copies your file into the caller's EXTRA_OUTPUT. If there is no EXTRA_OUTPUT, it returns a downscaled thumbnail bitmap in data. respondWithVideo(path) copies the file into EXTRA_OUTPUT, and if there is none, it returns a content:// URI from the plugin's own FileProvider, with FLAG_GRANT_READ_URI_PERMISSION set and the grant carried through ClipData. cancel() returns RESULT_CANCELED. Each of these sets the result and then finishes the activity.

Untrusted input stays untrusted. EXTRA_OUTPUT is validated before anything is written to it. Malformed or out-of-range extras are never passed on as they are: hour: 25 becomes null. Unknown parcelables in the extras are dropped, never unparcelled into Dart, and a malformed bundle is caught and does not crash the activity.

How to use it

Add it from GitHub:

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

It needs minSdk 21.

The plugin adds no intent filters to your app. You choose which requests your activity answers. Its own manifest contributes only a FileProvider that shares the cache/system_intents/ directory.

For camera capture, add filters inside your existing MainActivity element, next to the MAIN/LAUNCHER filter. The DEFAULT category is required, because implicit intents only match activities that declare it:

<intent-filter>
    <action android:name="android.media.action.IMAGE_CAPTURE" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
    <action android:name="android.media.action.VIDEO_CAPTURE" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Enter fullscreen mode Exit fullscreen mode

For alarms and timers, Android documents that handlers for SET_ALARM and SET_TIMER should require com.android.alarm.permission.SET_ALARM. If you put that permission on MainActivity itself, the launcher could no longer open your app. The README's answer is an activity-alias that points at MainActivity and carries the permission, with the alarm and timer actions in its filter. The full XML is in the README, and the example app contains a complete manifest.

Keep Flutter's default singleTop launch mode. Capture callers use startActivityForResult without FLAG_ACTIVITY_NEW_TASK, so Android creates a fresh instance of your activity in the caller's task, and that instance returns the result. Avoid singleTask and singleInstance for capture handling.

You can test a filter from the command line:

adb shell am start -a android.media.action.IMAGE_CAPTURE
Enter fullscreen mode Exit fullscreen mode

Then, in Dart:

import 'package:system_intents/system_intents.dart';

Future<void> handleLaunch() async {
  final intent = await SystemIntents.initialIntent();
  if (intent != null) await handle(intent);
  SystemIntents.intents.listen(handle); // later intents via onNewIntent
}

Future<void> handle(SystemIntent intent) async {
  switch (intent) {
    case ImageCaptureRequest():
      final path = await takePhotoSomehow(); // your camera UI
      if (path == null) {
        await SystemIntents.cancel();
      } else {
        await SystemIntents.respondWithImage(path); // finishes the activity
      }
    case SetAlarmRequest(:final hour, :final minutes, :final days):
      if (hour != null) {
        scheduleAlarm(hour, minutes ?? 0, days, silent: intent.isSilent);
      }
      if (!intent.skipUi) openAlarmEditor();
    case SetTimerRequest(:final length):
      if (length != null) startTimer(length);
    default:
      break;
  }
}
Enter fullscreen mode Exit fullscreen mode

takePhotoSomehow, scheduleAlarm, openAlarmEditor and startTimer are your app's own code. The README's version lists every case of the sealed type instead of using default.

When a reply fails, it throws a PlatformException whose code is one of the SystemIntentsErrorCodes: no_capture_request (the current intent is not the matching capture request, or it was already answered), invalid_output_uri (EXTRA_OUTPUT failed validation; the activity stays open, so call cancel()), file_not_found, write_failed and no_activity.

Security

EXTRA_OUTPUT comes from another app. Before writing, the plugin checks it against these rules:

  • A content:// URI is accepted only when the provider for its authority belongs to the calling package, resolved with PackageManager.resolveContentProvider.
  • content:// URIs served by your own app are always rejected. A caller could otherwise make you overwrite your own databases or preferences through your providers.
  • file:// is accepted only below API 24. Even then, a path that canonicalises into your app's private storage is rejected, including .. traversal.
  • Every other scheme is rejected.

Because capture requests use startActivityForResult, Activity.getCallingPackage() names the requesting app, and the plugin exposes it as SystemIntent.callingPackage. You can show it to the user or check it against an allow-list before you reply. It is null when the caller used plain startActivity, and that caller cannot receive a result anyway.

Things to know

  • Being the default is the user's choice. Declaring the filters only adds your app to the chooser. Android lets the user pick a handler or set a default, and apps must not try to force or trick that choice. Many callers also target a specific camera package directly, and they will never reach your app.
  • The package does no capturing itself. Use your own camera UI and pass the resulting file path.
  • The alarm and timer types only parse requests. Scheduling alarms is up to your app.
  • Thumbnails are at most 320 px on the longest edge, and EXIF orientation is not applied to them.
  • Third-party output URIs are refused. A caller that passes a URI from a third provider, such as a MediaStore row it inserted, is refused, and your app can then only cancel().
  • callingPackage is read from the activity. For intents delivered through onNewIntent, it reflects the activity's original caller.
  • Requests sent with adb shell am start have no calling package, so replies with an EXTRA_OUTPUT to them are refused.
  • What was tested. Kotlin tests cover the pure logic: extraction, weekday mapping, URI rules and thumbnail sizing. The example app has an emulator integration test in which a tiny second app calls startActivityForResult like a real client. It checks the typed requests, the reply written into the caller's EXTRA_OUTPUT, the thumbnail, the FileProvider video URI with its read grant, the refusal of a MediaStore EXTRA_OUTPUT, and SET_ALARM through the permission-guarded alias. It was tested on the Android Emulator (Pixel 10 system image, API 37) with a test caller app. It has not yet been tested on a physical phone or with third-party camera clients.

Why I built it

The problem in the README is the distance between "add an intent filter" and a handler that behaves correctly. The filter is four lines of XML. The rest is the part that goes wrong: extras that may be missing or out of range, an output URI chosen by a stranger, the thumbnail fallback, the URI permission grant for video, the alarm permission that must not sit on the launcher activity.

I wanted the Dart side to see only clean, typed requests, and the Kotlin side to refuse anything unsafe by default. A camera app that writes wherever a caller tells it to is a way into its own private files, so the URI rules are part of the plugin and not left as an exercise.

Get the code

The source, the full manifest guide, the example app and the tests are on GitHub: https://github.com/AbdeldjalilChougui/system_intents. It is MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)