Orientação gerada a partir de informações públicas. Apenas para referência.
O pacote receive_intent é um plugin do Flutter que permite que aplicativos Flutter recebam e processem Intents do Android, possibilitando uma comunicação fluida entre componentes nativos do Android e o ambiente do Flutter. Ele suporta o lançamento do aplicativo por meio de intents externas, como URLs, compartilhamento de arquivos ou ações personalizadas, tornando-o ideal para links profundos e interações entre aplicativos. O plugin fornece uma API simples para acessar dados de intent, como extras, ação e URI de dados. É especialmente útil para aplicativos que precisam responder a gatilhos externos de outros aplicativos ou eventos do sistema no Android.
Casos de uso
Manipulação de links profundos
Recebendo arquivos compartilhados
Processamento de esquemas de URL personalizados
Iniciando aplicativo de fontes externas
Integração com receptores de broadcast do Android
Principais recursos
Acesso simples aos dados de intenção
Suporte a linkagem profunda
Gerencia conteúdo compartilhado
Funciona com filtros de intenção do Android
Leve e fácil de integrar
Indicado para
Aplicativos que exigem linkagem profunda
Integrações de compartilhamento de arquivos
Tratamento de esquema de URL personalizado
Cenários de interoperabilidade nativa do Android
Resposta de gatilho externo
Considerações
Funcionalidade exclusiva para Android
Requer configuração de manifesto do Android
Limitado à plataforma Android
Sem suporte para iOS
É necessário configurar o filtro de intenção adequado no AndroidManifest.xml
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
receive_intent
A Flutter plugin to pass Android Intents to the Flutter environment.
Intent in Android is the "payload" for the communication between and within apps. This plugin passes the Intent, that "started" the Activity to the flutter environment. It also passes any "new Intents" that are received (via Activity.onNewIntent) while the Activity is already "started".
If the Intent was "started" via startActivityForResult, then this plugin also sends additional information (package name, app signature and component class name) about the "calling" Android Component, and can send "result" back (via Activity.setResult) to it.
This plugin is in active development.
Any contribution, idea, criticism or feedback is welcomed.
Quick links
package
https://pub.dev/packages/receive_intent
Git Repo
https://github.com/daadu/receive_intent
Issue Tracker
https://github.com/daadu/receive_intent/issues
Use cases
OAuth based App Flip - This was the initial motivation for this plugin. The plugin can be used to pass the Intent sent by Google App to the flutter environment - where the consent UI is shown - once it is authorized (or not), the result is sent back to the Google App.
Deeplink/Applink - This plugin is a generic implementation of uni_links plugin. While this plugin passes "any" Intents, uni_links only passes app-link/deep-link Intents.
Receive Share Intents - This plugin is a generic implementation of receive_sharing_intent plugin. While this plugin passes "any" Intents, receive_sharing_intent only passes "android.intent.action.SEND" (or related) Intents.
In general, if you want other apps to "start" your app, then this plugin can pass the Intent that "triggered" it to the flutter environment of the app. These Intent will give the app understanding of why the app was started. Check Getting started section to implement this.
Getting started
Add <intent-filter> to AndroidMainfest.xml
You need to add <intent-filter> to android/app/src/main/AndroidManifest.xml file:
<manifest...><!-- ... other tags --><application...><activity...><!-- ... other tags --><!-- Describe Intent your app can receive with <intent-filter> --><intent-filter><actionandroid:name="RECEIVE_INTENT_EXAMPLE_ACTION" /><categoryandroid:name="android.intent.category.DEFAULT"/></intent-filter></activity></application></manifest>
In this example we want to receive Intent with action matching RECEIVE_INTENT_EXAMPLE_ACTION literal. This <intent-filter> should be added to the Activity that extends FlutterActivity (for project generated from template it is MainActivity).
<intent-filter> describes, what Intent the Activity is capable to recevie. To read more about "Intent and Intent Filter", encourage you to check official docs from Android.
Recevie and handle Intent that launched the Activity in Flutter
Inside flutter code, you can call ReceiveIntent.getInitialIntent() to get the Intent that started the Activity:
import'package:receive_intent/receive_intent.dart';
// ...Future<void> _initReceiveIntent() async {
// Platform messages may fail, so we use a try/catch PlatformException.try {
final receivedIntent = awaitReceiveIntent.getInitialIntent();
// Validate receivedIntent and warn the user, if it is not correct,// but keep in mind it could be `null` or "empty"(`receivedIntent.isNull`).
} onPlatformException {
// Handle exception
}
}
// ...
Listen for any new Intent while the Activity is already running
To listen to new Intent while the Activity is running, you can use the ReceiveIntent.receivedIntentStream stream:
import'package:receive_intent/receive_intent.dart';
// ...StreamSubscription _sub;
Future<void> _initReceiveIntentit() async {
// ... check initialIntent// Attach a listener to the stream
_sub = ReceiveIntent.receivedIntentStream.listen((Intent? intent) {
// Validate receivedIntent and warn the user, if it is not correct,
}, onError: (err) {
// Handle exception
});
// NOTE: Don't forget to call _sub.cancel() in dispose()
}
// ...
Send result to the calling Activity (Optional)
If the calling Activty has "started" this activity with startActivityWithResult then you can send back result to that activity when ready with ReceiveIntent.setResult:
To read more about "Starting Activities and Getting Results" pattern, encourage you to check official docs from Android.
Additionaly, in the case of activity started with startActivityWithResult, the Intent object will also have package name (intent.fromPackageName), app signatures (intent.fromSignatures) and component class name (intent.componentClassName) of the calling activity. This could be used to validate the calling app, so that sensitive information is not given to unintendent apps.
Tools to test it
You can test this with either adb or Intent Test app form Playstore.
adb
To invoke (start) our FlutterAcitivity with RECEIVE_INTENT_EXAMPLE_ACTION intent action name as mentioned in example <intent-filter>above:
adb shell 'am start -W -a RECEIVE_INTENT_EXAMPLE_ACTION -c android.intent.category.DEFAULT'
If you don't have adb in your path, but have $ANDROID_HOME env variable then use "$ANDROID_HOME"/platform-tools/adb ....
Note: Alternatively you could simply enter an adb shell and run the am commands in it.
Check example app
To know more or to get the working code check the example app.
Todo
Document API references properly
Receive Intent for non-Activity based intent-filter (BroadcastReceiver, Service)
Automatic testing
Contribute
Check the Todo section above, before you begin with any contribution.