<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matheus Henrique de Souza Fontenele on Medium]]></title>
        <description><![CDATA[Stories by Matheus Henrique de Souza Fontenele on Medium]]></description>
        <link>https://medium.com/@matheusdeveloper.henrique?source=rss-f7b76e54cd9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wD3RRhk7_AWhkWs0xi7AgA.jpeg</url>
            <title>Stories by Matheus Henrique de Souza Fontenele on Medium</title>
            <link>https://medium.com/@matheusdeveloper.henrique?source=rss-f7b76e54cd9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:44:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matheusdeveloper.henrique/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Securing App Content: Handling Screenshots and Screen Recording in Flutter for Android and iOS]]></title>
            <link>https://medium.com/@matheusdeveloper.henrique/securing-app-content-handling-screenshots-and-screen-recording-in-flutter-for-android-and-ios-e570c1c16edb?source=rss-f7b76e54cd9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e570c1c16edb</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Matheus Henrique de Souza Fontenele]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 11:40:56 GMT</pubDate>
            <atom:updated>2026-02-06T19:21:38.888Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello, folks, in this article I will explain how to prevent and listen to printscreen and recording events in your mobile app.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A62XcChfFCnQlvgSJ7pOnw.jpeg" /></figure><h3>Introduction</h3><p>The core concept of security is to <strong>hinder an attacker</strong> as much as possible, creating obstacles that prevent them from achieving their objective. This security isn’t limited to code obfuscation; it extends to higher-level layers, such as <strong>masking sensitive information</strong> like passwords and monetary values — while still allowing the user to view the content — and preventing the easy capture and sharing of app content.</p><p>Along these lines, it can be crucial to detect when a specific user is taking <strong>screenshots or recording sensitive screens</strong> within your app. Being able to trigger a specific action in response can be vital, depending on your app’s business rules.</p><h3>Summary</h3><ul><li><strong>Screenshots and Screen Recording on Android/iOS</strong></li><li><strong>Android Implementation</strong></li><li><strong>iOS Implementation</strong></li><li><strong>Flutter Implementation</strong></li><li><strong>Conclusion</strong></li></ul><h3>Screenshots and Screen Recording on Android/iOS</h3><p>Android and iOS have distinct approaches to handling screenshots and screen recording. It’s important to understand that while both systems monitor these actions, their defensive mechanisms differ significantly.</p><p>Rather than simply “stopping” the user’s physical input, the platforms provide APIs that allow the application to respond to these events — either by blocking the content from being captured or by notifying the system that a security breach has occurred.</p><h3>iOS</h3><p>iOS does not allow you to programmatically prevent screenshots or screen recordings from occurring, nor does it automatically obfuscate the captured content to prevent users from accessing it. However, iOS does provide the tools to <strong>listen for screenshot and recording events</strong>, allowing you to take specific actions in real-time.</p><h4>Android</h4><p>Android allows you to programmatically make screenshots and screen recordings appear <strong>completely black</strong>. This ensures that even if a user triggers a capture, the resulting file contains no visible data from your app.</p><p>However, there is a trade-off: while blocking is powerful, Android historically lacked reliable methods to detect <em>when</em> a recording was taking place. This changed recently with the release of <strong>Android 14 (API level 34)</strong>, which introduced a dedicated API to listen specifically for screenshot events.</p><h3>Android Implementation</h3><p>On Android, we have the option to make the resulting screenshot or screen recording content appear completely dark, effectively protecting the displayed information. Additionally, starting with <strong>Android 14 (API level 34)</strong>, the system now allows applications to listen for screenshot events.</p><pre>package com.example.security_screen_app<br><br>import android.os.Build<br>import android.util.Log<br>import android.view.WindowManager<br>import io.flutter.embedding.android.FlutterFragmentActivity<br>import io.flutter.embedding.engine.FlutterEngine<br>import io.flutter.plugin.common.MethodChannel<br><br>class MainActivity : FlutterFragmentActivity() {<br><br>    private val channel = &quot;screen.security&quot;<br>    private lateinit var methodChannel: MethodChannel<br><br>    private val screenCaptureCallback = ScreenCaptureCallback {<br>        onScreenCaptured()<br>    }<br><br>    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br><br>        methodChannel = MethodChannel(<br>            flutterEngine.dartExecutor.binaryMessenger,<br>            channel<br>        )<br><br>        methodChannel.setMethodCallHandler { call, result -&gt;<br>                when (call.method) {<br>                    &quot;secureModeOn&quot; -&gt; {<br>                        window.setFlags(<br>                            WindowManager.LayoutParams.FLAG_SECURE,<br>                            WindowManager.LayoutParams.FLAG_SECURE<br>                        )<br>                        result.success(null)<br>                    }<br>                    &quot;secureModeOff&quot; -&gt; {<br>                        window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)<br>                        result.success(null)<br>                    }<br>                    else -&gt; result.notImplemented()<br>                }<br>        }<br><br>            <br>    }<br><br>    override fun onStart() {<br>        super.onStart()<br><br>        if (Build.VERSION.SDK_INT &gt;= 34) {<br>            registerScreenCaptureCallback(mainExecutor, screenCaptureCallback)<br>        }<br>    }<br><br>    override fun onStop() {<br>        super.onStop()<br><br>        if (Build.VERSION.SDK_INT &gt;= 34) {<br>            unregisterScreenCaptureCallback(screenCaptureCallback)<br>        }<br>    }<br><br>    private fun onScreenCaptured() {<br>        methodChannel.invokeMethod(&quot;onScreenshot&quot;, null)<br>    }<br>}</pre><h3>iOS Implementation</h3><p>On iOS, there is no native way to automatically block or black out content when a user takes a screenshot or records the screen. However, the system does allow you to natively listen for screenshot and screen recording events in real-time.</p><pre>import UIKit<br>import Flutter<br><br>@main<br>@objc class AppDelegate: FlutterAppDelegate {<br><br>    private let CHANNEL = &quot;screen.security&quot;<br>    private var methodChannel: FlutterMethodChannel?<br><br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br><br>        guard let controller = window?.rootViewController as? FlutterViewController else {<br>            return false<br>        }<br><br>        methodChannel = FlutterMethodChannel(<br>            name: CHANNEL,<br>            binaryMessenger: controller.binaryMessenger<br>        )<br><br><br>        NotificationCenter.default.addObserver(<br>            self,<br>            selector: #selector(screenshotTaken),<br>            name: UIApplication.userDidTakeScreenshotNotification,<br>            object: nil<br>        )<br><br>        NotificationCenter.default.addObserver(<br>            self,<br>            selector: #selector(screenCaptureChanged),<br>            name: UIScreen.capturedDidChangeNotification,<br>            object: nil<br>        )<br><br><br>        UNUserNotificationCenter.current().delegate = self<br>        GeneratedPluginRegistrant.register(with: self)<br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }<br><br>  <br>    @objc func screenshotTaken() {<br>        methodChannel?.invokeMethod(&quot;onScreenshot&quot;, arguments: nil)<br>    }<br><br>    @objc func screenCaptureChanged() {<br>        let isCaptured = UIScreen.main.isCaptured<br>        methodChannel?.invokeMethod(&quot;onScreenRecording&quot;, arguments: isCaptured)<br>    }<br>}</pre><h3>Flutter Implementation</h3><p>In Flutter, we implemented secureModeOn and secureModeOff events; however, these functions are currently only effective on <strong>Android</strong>. To bridge the gap for <strong>iOS</strong> and <strong>Android 14+</strong>, we developed listeners to detect screenshot events, while screen recording detection remains exclusive to <strong>iOS.</strong></p><pre>import &#39;dart:developer&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:security_screen_app/main.dart&#39;;<br><br>class ScreenSecurityService {<br>  static const _channel = MethodChannel(&#39;screen.security&#39;);<br>  static bool _isShowingRecordingDialog = false;<br><br>  static void listenerScreenShotsEvents() {<br>    _channel.setMethodCallHandler((call) async {<br>      switch (call.method) {<br>        case &quot;onScreenshot&quot;:<br>          log(&quot;📸 Screenshot detected&quot;, name: &quot;Screenshot&quot;);<br>          rootScaffoldMessengerKey.currentState?.showSnackBar(<br>            const SnackBar(<br>              content: Text(&quot;📸 Screenshot detected&quot;),<br>              duration: Duration(seconds: 2),<br>            ),<br>          );<br>          final context = rootNavigatorKey.currentContext;<br>          if (context == null) return;<br><br>          showDialog(<br>            context: context,<br>            barrierDismissible: true,<br>            builder: (_) =&gt; const AlertDialog(<br>              title: Text(&quot;PrintScreen  Detected&quot;),<br>              content: Text(&quot;You take a screenshot.&quot;),<br>            ),<br>          );<br><br>          break;<br><br>        case &quot;onScreenRecording&quot;:<br>          final bool isRecording = call.arguments;<br>          log(&quot;🎥 Screen recording: $isRecording&quot;, name: &quot;Screen Recording&quot;);<br><br>          final context = rootNavigatorKey.currentContext;<br>          if (context == null) return;<br><br>          if (isRecording &amp;&amp; !_isShowingRecordingDialog) {<br>            _isShowingRecordingDialog = true;<br><br>            showDialog(<br>              context: context,<br>              barrierDismissible: true,<br>              builder: (_) =&gt; const AlertDialog(<br>                title: Text(&quot;Screen Recording Detected&quot;),<br>                content: Text(&quot;Your screen is being recorded.&quot;),<br>              ),<br>            );<br>          }<br><br>          if (!isRecording &amp;&amp; _isShowingRecordingDialog) {<br>            _isShowingRecordingDialog = false;<br>          }<br><br>          break;<br>      }<br>    });<br>  }<br><br>  static Future&lt;void&gt; secureModeOn() async {<br>    if (Platform.isAndroid) {<br>      try {<br>        await _channel.invokeMethod(&#39;secureModeOn&#39;);<br>      } catch (e) {<br>        rethrow;<br>      }<br>    }<br>  }<br><br>  static Future&lt;void&gt; secureModeOff() async {<br>    if (Platform.isAndroid) {<br>      try {<br>        await _channel.invokeMethod(&#39;secureModeOff&#39;);<br>      } catch (e) {<br>        rethrow;<br>      }<br>    }<br>  }<br>}</pre><h3>Conclusion</h3><p>Although these features are highly situational, this knowledge can be very valuable depending on your business rules. I hope you enjoyed the article, and you can find the complete implementation at this link on my <a href="https://github.com/MatheusHenriq/SecurityScreenApp"><strong>GitHub</strong></a>.</p><p>I hope the article helps you, and I’ll see you soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*__qsKtoqm1c8Q4zv.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e570c1c16edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Your Android Deploys: How to Enable the Google Play API for Internal Testing.]]></title>
            <link>https://medium.com/@matheusdeveloper.henrique/automate-your-android-deploys-how-to-enable-the-google-play-api-for-internal-testing-d67b785f80f6?source=rss-f7b76e54cd9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d67b785f80f6</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Matheus Henrique de Souza Fontenele]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 22:22:08 GMT</pubDate>
            <atom:updated>2026-04-08T13:39:35.195Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello guys, in this article i will explain how to setup Google Play API for Android internal tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ji5CGRk07UUy1w0jUPxgWg.jpeg" /></figure><h3>Introduction</h3><p>The main point, in my opinion, of creating <strong>CI/CD pipelines</strong> is to provide a greater guarantee that the product we are delivering has the <strong>lowest possible number of bugs</strong> (it would be great if there were none) and the <strong>speed of software delivery</strong> to the final destination, which can be a testing environment in the development or staging phase, such as Firebase App Distribution, or to the final customer in Android internal tests or iOS TestFlight.</p><h3>Main Goal</h3><p>The article aims to explain how to set up the <strong>Google environment</strong> to use <strong>Android application deployments for internal tests</strong> within <strong>CD pipelines</strong>. As examples, the article shows how to utilize this knowledge in <strong>GitHub Actions</strong> and <strong>Azure DevOps</strong> pipelines.</p><h3>Permissions and Access</h3><p>To continue reading the article, it is of utmost importance that:</p><ul><li>The project is <strong>linked to Firebase</strong>.</li><li>The project has a <strong>store listing on Google Play Console</strong></li><li>The project has been <strong>published at least once in internal tests</strong>.</li><li>ou have <strong>Editor access or higher roles in the project’s Google Cloud (Gcloud)</strong>.</li><li>You have <strong>Admin access in the Google Play Console</strong>.</li></ul><blockquote>Of course, if you are reading the article and do not have these accesses and permissions, but your teammate does, continue reading the article, pass the knowledge on to them, and practice <strong>pair programming</strong>.</blockquote><p>Once all the above conditions have been met, let’s proceed to the step-by-step guide.</p><h3>Step-by-step</h3><ol><li><strong>Create the Access Key</strong></li></ol><p>Access Gcloud -&gt; <strong>IAM -&gt; Service Accounts</strong></p><p>Upon accessing the Service Accounts, you can create a new service account, specifying a name, such as: githubactions-deploy@yourproject.iam.gserviceaccount.com. Alternatively, you can just click on an existing one.</p><p>When you click on your account, go to: <strong>Keys -&gt; Add Key -&gt; Create new key</strong> and select the <strong>JSON</strong> key type</p><p><strong>2. Activating the Google Play Android Developer API</strong></p><p>Still in <strong>Gcloud</strong>, access the <strong>hamburger menu</strong> (sandwich menu) on the top left and select the option <strong>APIs &amp; Services</strong> -&gt; In the search bar, type “<strong>Google Play Android Developer API</strong>” -&gt; <strong>Enable</strong></p><p><strong>3. Linking the service in the Google Play Console</strong></p><p>Once you have downloaded the <strong>JSON key</strong>, extract the &quot;client_email&quot; from it.</p><p>On the Google Play Console homepage, select your store, then navigate to the left sidebar menu -&gt; <strong>Users and permissions</strong> -&gt; <strong>Invite new users</strong> -&gt; Add the &quot;client_email&quot; with access to the correct app and add the permissions for <strong>App access (except admin)</strong> and <strong>Releases</strong>.</p><h3>Testing in <strong>Azure DevOps</strong> and <strong>GitHub Actions</strong>.</h3><p>Azure DevOps and GitHub Actions work in a different way. While Azure DevOps has a <strong>low dependency on the community</strong>, and its packages are validated beforehand by the Microsoft team, <strong>GitHub Actions relies on the community</strong>, making it possible to find multiple packages with the same purpose — some with more and some with fewer configurations.</p><ol><li><strong>Azure Devops</strong></li></ol><p>In Azure DevOps, to enable the <strong>Release task to Google</strong>, you first need to configure the <strong>Service Connection</strong>. To do this, access the <strong>Azure project settings</strong> -&gt; <strong>Service connections</strong> -&gt; <strong>New service connection</strong> -&gt; <strong>Google Play</strong>, and a screen in this format will open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ujhRX7wBnaVFITmeEVhkWw.png" /></figure><p>The most important pieces of information are the <strong>Private Key</strong> and the <strong>Service Account Email</strong>. Both pieces of information are found in the JSON file, under the keys &quot;client_email&quot; and &quot;private_key&quot;.</p><p><strong>Service Connection Name</strong> and <strong>Description</strong> are just identifiers to make it easier to identify the purpose of this service connection.</p><p>Once this is done, the <strong>Google Play — Release</strong> task can be added to the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*4AnxFG2cW3R7jkLAnPJGpA.png" /></figure><p>And in its <strong>service connection</strong>, assign the previously created service connection.</p><p>2. <strong>Github actions</strong></p><p>Since <strong>GitHub Actions</strong> is a tool that allows the community to maintain the packages, it is important to pay attention to the package’s <strong>popularity</strong> and how many people contribute to it. In the case of this article, the most highly rated package is <a href="https://github.com/marketplace/actions/upload-android-release-to-play-store"><strong>Upload Android Release to Play Store</strong></a> by <a href="https://github.com/r0adkll">Drew Heavner</a>, which has 25 contributors.</p><p>Here&#39;s the code example:</p><pre>uses: r0adkll/upload-google-play@v1<br>with:<br>  serviceAccountJsonPlainText: ${{ SERVICE_ACCOUNT_JSON }}<br>  packageName: com.example.MyApp<br>  releaseFiles: app/build/outputs/bundle/release/app-release.aab<br>  track: production<br>  status: inProgress<br>  inAppUpdatePriority: 2<br>  userFraction: 0.33<br>  whatsNewDirectory: distribution/whatsnew<br>  mappingFile: app/build/outputs/mapping/release/mapping.txt<br>  debugSymbols: app/intermediates/merged_native_libs/release/out/lib</pre><p>It is important to emphasize that some of these fields are <strong>optional</strong> and should only be used if the build is delivered in a <strong>staged rollout</strong> to the general public.</p><p>The <a href="https://github.com/marketplace/actions/upload-android-release-to-play-store"><strong>GitHub</strong></a> page has all the important information you need to make the delivery correctly.</p><h3>Conclusion</h3><p>The <strong>speed of delivery</strong> to the right environment and to the right testers is very important to ensure faster validations and thereby <strong>reduce the time-to-market</strong> for the final customer.</p><p>By following the steps contained in the article, the service will function regardless of the platform you use to build your pipelines.</p><p>I hope the article helps you, and I’ll see you soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ycfiiMAbrGSW7Ygo.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d67b785f80f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Live Activity: From Development to Testing]]></title>
            <link>https://medium.com/@matheusdeveloper.henrique/flutter-live-activity-from-development-to-testing-a4fcca6325d9?source=rss-f7b76e54cd9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4fcca6325d9</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[live-activities]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Matheus Henrique de Souza Fontenele]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 23:58:52 GMT</pubDate>
            <atom:updated>2025-01-16T10:58:28.724Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello, folks, In this tutorial we will talk about what live activity is, how to implement this feature and link it to our flutter app and test this feature locally and via API like a real application works.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-AcI7lfVqXZjMwQgCvaew.png" /></figure><h3><strong>Summary</strong></h3><ul><li>Introduction</li><li>Setting up Xcode</li><li>Setting up Certificate and keys(need to be part of a development team and make available to test our live activity via API)</li><li>Setting up info.plist</li><li>Creating Live activity</li><li>Swift implementation</li><li>Flutter implementation</li><li>Test live activities locally</li><li>Test live activities via API</li><li>Conclusion</li></ul><h3><strong>Introduction</strong></h3><p>Live activity is an iOS feature that allow the application to display up-to-date information with a fancy way. In other words, it&#39;s like to push notifications that allow you to update data and customize the layout of this push notification.</p><p>This feature is available since 2022, on iOS 16.2 version, and it is super important because users that have iOS devices with a version below 16.2 will not be able to receive live activities.</p><h3><strong>Setting up Xcode</strong></h3><p>In Xcode, open xcworkspace from your flutter project, click on Runner -&gt; Signing &amp; Capabilities and add Push Notification and Background Modes-&gt;Remote Notification and background fetch. These respective capabilites will let your app receive live activities when it is in foreground mode and when it&#39;s closed. Background modes with these two capabilities(Remote Notification and background fetch) will make our app available to receive live activity via API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfT75q8Eih0G28ZdsdFW_g.png" /></figure><p><strong>Setting up Certificate and Keys</strong></p><p><em>If you wanna test it via API, keep reading this section</em></p><p>Access <a href="https://developer.apple.com/account/resources">Certificate, Identifiers and profiles</a> and create an identifier for your app (with the same bundleId from your flutter app, obviously) and enable Push notifications.</p><p>After that, select keys on the side bar and enable Apple Push Nofitication service(APNS) and Install the .p8 file in your computer right after you create it.</p><h3>Setting up info.plist</h3><p>Access your info.plist and add:</p><pre> &lt;key&gt;NSSupportsLiveActivities&lt;/key&gt;<br> &lt;true/&gt;<br> &lt;key&gt;NSSupportsLiveActivitiesFrequentUpdates&lt;/key&gt;<br> &lt;true/&gt;</pre><h3><strong>Creating Live activity</strong></h3><p>Open your Xcode and click on Runner -&gt; add a new target -&gt; Widget Extension</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*sSR1u8vUI07h2d-wnblqfA.png" /></figure><p>Make sure that your app will be linked to the correct Team. If you want to test it via API link this to your Development Team, this Development team should be the same as the Runner (targets)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*zyJ-sOU_vVQLKW_FqYybtw.png" /></figure><p>It will create a folder with three files: LiveActivityWidgetBundle, LiveActivityWidgetLiveActivity, LiveActivityWidget. We will focus our effors on LiveActivityWidgetLiveActivity.</p><p>Our live activity will have this code:</p><pre>import ActivityKit<br>import WidgetKit<br>import SwiftUI<br><br>struct LiveActivityWidgetAttributes: ActivityAttributes {<br>    public struct ContentState: Codable, Hashable {<br>        var driverCode : String<br>        var carModel : String<br>        var minutesToArrive: Int<br>        var carArriveProgress: Int<br>    }<br>}<br><br>struct LiveActivityWidgetLiveActivity: Widget {<br>    var body: some WidgetConfiguration {<br>        ActivityConfiguration(for: LiveActivityWidgetAttributes.self) { context in<br>            if(context.state.carArriveProgress &lt; 100) {<br>                CarArravingView(context: context).activityBackgroundTint(Color.black.opacity(0.7))<br>            }else{<br>                CarArrivedView(context: context).activityBackgroundTint(Color.black.opacity(0.7))<br>            }<br>        } dynamicIsland: { context in<br>            DynamicIsland {<br>                DynamicIslandExpandedRegion(.leading) {<br>                    if(context.state.carArriveProgress &lt; 100){<br>                        Text(&quot;Pickup in&quot;).foregroundColor(.white).padding(EdgeInsets(top: 4, leading: 12, bottom: 0, trailing: 12))<br>                    }else{<br>                        Text(&quot;Driver Arrives&quot;).foregroundColor(.white).padding(EdgeInsets(top: 4, leading: 12, bottom: 0, trailing: 12))<br>                    }<br>                   <br>                }<br>                DynamicIslandExpandedRegion(.trailing) {<br>                    if(context.state.carArriveProgress &lt; 100){<br>                        Text(&quot;\(context.state.minutesToArrive) min&quot;).foregroundColor(.white).padding(EdgeInsets(top: 4, leading: 12, bottom: 0, trailing: 12))<br>                    }else{<br>                        Text(&quot;Enjoy your trip&quot;).foregroundColor(.white).padding(EdgeInsets(top: 4, leading: 12, bottom: 0, trailing: 12))<br>                    }<br>                   <br>                }<br>                DynamicIslandExpandedRegion(.bottom) {<br>                    if(context.state.carArriveProgress &lt; 100){<br>                        ProgressBarWithCar(progress: context.state.carArriveProgress).padding(EdgeInsets(top: 0, leading: 42, bottom: 0, trailing: 42))<br>                    }else{<br>                        ZStack(alignment: Alignment(horizontal: .center, vertical: .center), content: {<br>                            Circle().fill(Color.blue).frame(width: 52,height: 52)<br>                            Image(&quot;flag&quot;).resizable().frame(width: 42,height: 42).scaledToFit().aspectRatio(contentMode: .fit)<br>                        })<br>                    }<br>                  <br>                }<br>            } compactLeading: {<br>                if(context.state.carArriveProgress &lt; 100){Text(&quot;Pickup in&quot;).foregroundColor(.white)}<br>                else{Text(&quot;Driver Arrives&quot;).foregroundColor(.white)}<br>                <br>            } compactTrailing: {<br>                if(context.state.carArriveProgress &lt; 100){ Text(&quot;\(context.state.minutesToArrive) min&quot;).foregroundColor(.white)}<br>                else{  ZStack(alignment: Alignment(horizontal: .center, vertical: .center), content: {<br>                    Circle().fill(Color.blue).frame(width: 32,height: 32)<br>                    Image(&quot;flag&quot;).resizable().frame(width: 25,height: 25).scaledToFit().aspectRatio(contentMode: .fit)<br>                })}<br>            } minimal: {<br>                if(context.state.carArriveProgress &lt; 100){Text(&quot;Driver on the way&quot;).foregroundColor(.white)}<br>                else{Text(&quot;Driver Arrives&quot;).foregroundColor(.white)}<br>            }<br>        }<br>    }<br>}<br><br>extension LiveActivityWidgetAttributes {<br>    fileprivate static var preview: LiveActivityWidgetAttributes {<br>        LiveActivityWidgetAttributes()<br>    }<br>}<br><br>extension LiveActivityWidgetAttributes.ContentState {<br>    fileprivate static var model1: LiveActivityWidgetAttributes.ContentState {<br>        LiveActivityWidgetAttributes.ContentState(driverCode: &quot;Matheus&quot;, carModel: &quot;Virtus&quot;, minutesToArrive: 10, carArriveProgress: 30)<br>     }<br>     <br>    fileprivate static var model2 : LiveActivityWidgetAttributes.ContentState {<br>         LiveActivityWidgetAttributes.ContentState(driverCode: &quot;Matheus&quot;, carModel: &quot;Virtus&quot;, minutesToArrive: 10, carArriveProgress: 30)<br>     }<br>}<br><br>#Preview(&quot;Notification&quot;, as: .content, using: LiveActivityWidgetAttributes.preview) {<br>   LiveActivityWidgetLiveActivity()<br>} contentStates: {<br>    LiveActivityWidgetAttributes.ContentState.model1<br>    LiveActivityWidgetAttributes.ContentState.model2<br>}<br><br>struct CarArravingView : View{<br>    let context: ActivityViewContext&lt;LiveActivityWidgetAttributes&gt;<br><br>    init(context: ActivityViewContext&lt;LiveActivityWidgetAttributes&gt;) {<br>          self.context = context<br>    }<br>    <br>    var body : some View{<br>        VStack{<br>            HStack(alignment:.center, content: {<br>                VStack(alignment: .leading, content: {<br>                    Text(&quot;Pickup in \(context.state.minutesToArrive) min&quot;).semiBold20() .padding(EdgeInsets(top: 4, leading: 0, bottom: 0, trailing: 2))<br>                    Text(&quot;\(context.state.driverCode) - \(context.state.carModel)&quot;).regular16()<br>                })<br>                Spacer()<br>                ZStack(alignment: Alignment(horizontal: .center, vertical: .center), content: {<br>                    Circle().fill(Color.blue).frame(width: 48,height: 48)<br>                    Image(&quot;driver&quot;).resizable().frame(width: 32,height: 32).scaledToFit().aspectRatio(contentMode: .fit)<br>                })<br>                   <br>                <br>            })<br>           <br>                ProgressBarWithCar(progress: context.state.carArriveProgress)<br>           <br>            <br>    }.padding(EdgeInsets(top: 12, leading: 42, bottom: 0, trailing: 42))<br>    }<br>}<br><br>struct CarArrivedView : View{<br>    let context: ActivityViewContext&lt;LiveActivityWidgetAttributes&gt;<br><br>    init(context: ActivityViewContext&lt;LiveActivityWidgetAttributes&gt;) {<br>          self.context = context<br>    }<br>    <br>    var body : some View{<br>        VStack{<br>            HStack(alignment:.center, content: {<br>                VStack(alignment: .leading, content: {<br>                    Text(&quot;Your Driver Arrives&quot;).semiBold20() .padding(EdgeInsets(top: 4, leading: 0, bottom: 0, trailing: 2))<br>                    Text(&quot;Have a confort trip&quot;).regular16()<br>                })<br>                Spacer()<br>                ZStack(alignment: Alignment(horizontal: .center, vertical: .center), content: {<br>                    Circle().fill(Color.blue).frame(width: 52,height: 52)<br>                    Image(&quot;flag&quot;).resizable().frame(width: 42,height: 42).scaledToFit().aspectRatio(contentMode: .fit)<br>                })<br>                   <br>            })<br>           <br>            <br>    }.padding(EdgeInsets(top: 12, leading: 42, bottom: 16, trailing: 42))<br>    }<br>}<br><br><br>struct ProgressBarWithCar: View {<br>   var progress: Int = 0<br>    @State private var barWidth: CGFloat = 0<br>    init(progress: Int ) {<br>        self.progress = progress<br>    }<br>    var body: some View {<br>        VStack {<br>            ZStack(alignment: .leading) {<br>                ProgressView(value: Double(self.progress), total: 100)<br>                    .progressViewStyle(LinearProgressViewStyle(tint: .white)).background(Color.gray.opacity(0.4)).frame(height: 28)<br>                                        .cornerRadius(6)<br>                    .overlay(<br>                        GeometryReader { geometry in<br>                            Color.clear.onAppear {<br>                                self.barWidth = geometry.size.width<br>                            }<br>                        }<br>                    )<br><br>                ZStack {<br>                    Image(&quot;car&quot;)<br>                        .resizable()<br>                        .frame(width: 32, height: 42)<br>                        .scaledToFit()<br>                }<br>                .offset(x: CGFloat(Double(self.progress) / 100) * barWidth - 32)<br>            }<br>            .padding(EdgeInsets(top: 0, leading: 0, bottom: 4, trailing: 0))<br>            <br>           <br>        }<br>    }<br>}<br><br>extension Text {<br>   <br>    func semiBold20() -&gt; some View {<br>        self.fontWeight(.semibold).font(.system(size: 20)).foregroundColor(.white)<br>    }<br>    <br>    func regular16() -&gt; some View {<br>        self.fontWeight(.regular).font(.system(size: 16)).foregroundColor(.gray.opacity(0.8))<br>    }<br>}</pre><p>Once it is concluded, go to Runner -&gt; Targets -&gt; Runner -&gt; Build Phases and verify if the phases have this order on the bottom</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_cA5enOpis72FCY55GANg.png" /></figure><p>Sometimes when we create our live activity it is not compile because phases are in a wrong order.</p><p>Live activities could display information on the Lock Screen, on iPhone in StandBy, and the Dynamic Island.</p><p>If you are not familiarized with dynamic island, it is that part of your iphone</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQl_K-fNRqMKSOEVsCWBPQ.jpeg" /></figure><p>You could see in the code above, that we implemented our Live Activity on differents locations of our iphone:</p><p><strong>ActivityConfiguration</strong> shows on lockscreen and standby, <strong>dynamicIsland</strong> show on the dynamic island when it is expanded an when it is compact, in this image above, the first phone is the dynamic island compact and the second is dynamic island expanded.</p><h3><strong>Swift Implementation</strong></h3><p>Once you finished to create your live activity, we will dive into our swift code.</p><p>First we will create a file to handle Live activities, it&#39;s important if you want to test it locally.</p><p>Go to Runner -&gt; Click on Runner folder and select new -&gt; Select Swift File and create LiveActivityManager, it&#39;s important to link this file to Runner and LiveActivityWidgetExtension, because we will make references to structs created on LiveActivityWidgetExtension files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*E8_-9vqleZjoCrXdEfJ2Yg.png" /></figure><p>and we will put this code inside LiveActivityManager:</p><pre><br>import Foundation<br>import ActivityKit<br><br>@available(iOS 16.2, *)<br>class LiveActivityManager {<br>    private var liveActivity: Activity&lt;LiveActivityWidgetAttributes&gt;? = nil<br>       <br>   <br>    func startLiveActivity(data: [String: Any]?) {<br>        let attributes = LiveActivityWidgetAttributes()<br>        if let info = data {<br>            let state =  LiveActivityWidgetAttributes.ContentState(<br>                driverCode: info[&quot;driverCode&quot;] as? String ?? &quot;&quot;, carModel: info[&quot;carModel&quot;] as? String ?? &quot;&quot;, minutesToArrive: info[&quot;minutesToArrive&quot;] as? Int ?? 0, carArriveProgress: info[&quot;carArriveProgress&quot;] as? Int ?? 0<br>            )<br>            Task{<br>                liveActivity = try? Activity&lt;LiveActivityWidgetAttributes&gt;.request(attributes: attributes,  content: .init(state: state, staleDate: nil), pushType: .token)<br>                }<br>            }<br>        <br>    }<br><br>    func updateLiveActivity(data: [String: Any]?) {<br>        if let info = data {<br>        let updatedState = LiveActivityWidgetAttributes.ContentState(<br>            driverCode: info[&quot;driverCode&quot;] as? String ?? &quot;&quot;, carModel: info[&quot;carModel&quot;] as? String ?? &quot;&quot;, minutesToArrive: info[&quot;minutesToArrive&quot;] as? Int ?? 0, carArriveProgress: info[&quot;carArriveProgress&quot;] as? Int ?? 0<br>           )<br>        Task {<br>          await liveActivity?.update(using: updatedState)<br>        }<br>      } <br>    }<br>    <br>  <br>    func endLiveActivity() {<br>        Task {<br>            await self.liveActivity?.end(dismissalPolicy: .immediate)<br>        }<br>    }<br>}<br></pre><p>If you ant to test it only locally and do not allow background modes on capabilities, set pushType to nil in startLiveActivity, when we use .token we make available our service to start locally and start, update, end via API with a token-based connection.</p><p>You could notice that start and update functions receive data parameter that have to have 4 fields : driverCode, carModel, minutesToArrive and carArriveProgress. These fields match with LiveActivityWidgetAttributes on LiveActivityWidgetLiveActivity file.</p><p>Other important thing to do is access LiveActivityWidgetLiveActivity to set Runner in Target Membership</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DbAROwyUzAFIODDOblZBA.png" /></figure><p>After that, on AppDelegate.swift, put this code:</p><pre>import Flutter<br>import ActivityKit<br>import UIKit<br><br>//if you will test only locally, delete FlutterStreamHandler<br>@main<br>@objc class AppDelegate: FlutterAppDelegate, FlutterStreamHandler {<br>    let channelName : String = &quot;liveActivityChannel&quot;<br>    //only if you will test via API<br>    let eventName : String = &quot;LiveActivityEvents&quot;<br>    //only if you will test via API<br>    var eventSink: FlutterEventSink?<br>    //only if you will test via API<br>    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -&gt; FlutterError? {<br>            self.eventSink = events<br>            return nil<br>    }<br>    //only if you will test via API<br>    func onCancel(withArguments arguments: Any?) -&gt; FlutterError? {<br>            return nil<br>    }<br>    //only if you will test via API<br>    private func sendEvent(value: Dictionary&lt;String,Any?&gt;) {<br>               guard let eventSink = self.eventSink else { return }<br>               eventSink(value)<br>    }<br>    <br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController<br>        let liveActivityChannel = FlutterMethodChannel(name: channelName, binaryMessenger: controller.binaryMessenger)<br>         //only if you will test via API        <br>         if #available(iOS 10.0, *) {<br>            UNUserNotificationCenter.current().delegate = self<br>        }<br>        let liveActivityManager = LiveActivityManager()<br>        liveActivityChannel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in<br>            switch call.method {<br>            //only if you will test via API<br>            case &quot;registerDevice&quot;:<br>                self?.registerDevice(application: application, result: result)<br>                result(true)<br>            //only if you will test via API<br>            case &quot;requestForNotificationPermission&quot;:<br>                self?.requestNotificationPermissions(result: result)<br>                result(true)<br>                break<br>            case &quot;startLiveActivity&quot;:<br>                liveActivityManager.startLiveActivity(data: call.arguments as? Dictionary&lt;String,Any&gt;)<br>                result(true)<br>                break<br>            case &quot;updateLiveActivity&quot;:<br>                liveActivityManager.updateLiveActivity(data: call.arguments as? Dictionary&lt;String,Any&gt;)<br>                result(true)<br>                break<br>            case &quot;endLiveActivity&quot;:<br>                liveActivityManager.endLiveActivity()<br>                result(true)<br>                break<br>            default:<br>                result(FlutterMethodNotImplemented)<br>            }}<br>          <br>            //observe every change in pushToStartToken and pushToUpdateToken<br>            //when some change occurs, it will send to out eventChannel that we can retrive via flutter code<br>            //only if you will test via API<br>            observePushToStartToken()<br>            //only if you will test via API<br>            observePushUpdateToken()<br>            //only if you will test via API<br>            let eventChannel = FlutterEventChannel(name:  eventName, binaryMessenger: controller.binaryMessenger)<br>            //only if you will test via API<br>            eventChannel.setStreamHandler(self)<br>            GeneratedPluginRegistrant.register(with: self)<br>            return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>        }<br>        //only if you will test via API<br>        override func userNotificationCenter(_ center: UNUserNotificationCenter,<br>                                             willPresent notification: UNNotification,<br>                                             withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void) {<br>            if #available(iOS 14.0, *) {<br>                completionHandler([.banner, .list, .sound, .badge])<br>            } else {<br>                completionHandler([.alert, .sound, .badge])<br>            }<br>        }<br>        //only if you will test via API<br>        override func userNotificationCenter(_ center: UNUserNotificationCenter,<br>                                             didReceive response: UNNotificationResponse,<br>                                             withCompletionHandler completionHandler: @escaping () -&gt; Void) {<br>            _ = response.notification.request.content.userInfo<br>            completionHandler()<br>        }<br><br>        private func registerDevice(application: UIApplication, result: @escaping FlutterResult) {<br>            application.registerForRemoteNotifications()<br>            result(&quot;Device Token registration initiated&quot;)<br>        }<br>    //only if you will test via API<br>    private func requestNotificationPermissions(result: @escaping FlutterResult) {<br>            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in<br>            if let error = error {<br>                result(FlutterError(code: &quot;PERMISSION_ERROR&quot;, message: &quot;Failed to request permissions&quot;, details: error.localizedDescription))<br>                return<br>            }<br>                result(granted)<br>            }<br>        }<br>    //only if you will test via API<br>    func observePushToStartToken() {<br>                if #available(iOS 17.2, *)  {<br>                    Task {<br>                        for await data in Activity&lt;LiveActivityWidgetAttributes&gt;.pushToStartTokenUpdates {<br>                            let token = data.map {String(format: &quot;%02x&quot;, $0)}.joined()<br>                            print(&quot;pushToStartToken -&gt; \(token)&quot;)<br>                            sendEvent(value: [<br>                                &quot;eventType&quot; : &quot;pushToStartToken&quot;,<br>                                       &quot;value&quot;    :   token,<br>                                   ])<br>                            }<br>                    }<br>                <br>                }<br>            }<br>        //only if you will test via API<br>        func observePushUpdateToken() {<br>            if #available(iOS 16.2, *){<br>                Task {<br>                    for await activityData in Activity&lt;LiveActivityWidgetAttributes&gt;.activityUpdates {<br>                        Task {<br>                            for await tokenData in activityData.pushTokenUpdates {<br>                                let token = tokenData.map { String(format: &quot;%02x&quot;, $0) }.joined()<br>                                print(&quot;pushToUpdateToken -&gt; \(token)&quot;)<br>                                sendEvent(value: [<br>                                    &quot;eventType&quot; : &quot;pushToUpdateToken&quot;,<br>                                           &quot;value&quot;    :   token,<br>                                       ])<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    <br>}</pre><p>You can notice that if we only test it locally our appDelegate will contain less code, so why we need this bunch of code when we want to test via API?</p><p>Because to test it via API we need to:</p><ul><li>Make our app available to receive push nofication(apns-push-type liveactivity)</li><li>Need to Listen to two tokens: pushToStartToken(token that is used to start live activities) and pushToUpdateToken(token that is used to update and end live activities)</li><li>Send these two tokens to our flutter app to our flutter app send these tokens to server.</li></ul><h3>Flutter implementation</h3><p>create a service to handler the notification.</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:developer&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br><br>class LiveActivityModel {<br>  final String carModel;<br>  final String driverCode;<br>  final int minutesToArrive;<br>  final int carArriveProgress;<br>  LiveActivityModel({<br>    required this.carModel,<br>    required this.driverCode,<br>    required this.minutesToArrive,<br>    required this.carArriveProgress,<br>  });<br><br>  Map&lt;String, dynamic&gt; toJson() =&gt; {<br>        &#39;carModel&#39;: carModel,<br>        &#39;driverCode&#39;: driverCode,<br>        &#39;minutesToArrive&#39;: minutesToArrive,<br>        &#39;carArriveProgress&#39;: carArriveProgress,<br>      };<br>}<br><br>class LiveActivityService {<br>  static const platform = MethodChannel(&#39;liveActivityChannel&#39;);<br>  //only if you will test via API<br>  static const listenerChannel = EventChannel(&#39;LiveActivityEvents&#39;);<br>  //only if you will test via API<br>  StreamSubscription? eventSubscription;<br>  //only if you will test via API<br>  Future&lt;void&gt; listener() async {<br>    eventSubscription = listenerChannel.receiveBroadcastStream().listen(<br>      (event) async {<br>        switch (event[&#39;eventType&#39;]) {<br>          case &#39;pushToStartToken&#39;:<br>            dynamic tokenValue = event[&#39;value&#39;];<br>            log(&quot;pushToStartToken -&gt; $tokenValue&quot;);<br>            break;<br>          case &#39;pushToUpdateToken&#39;:<br>            dynamic tokenValue = event[&#39;value&#39;];<br><br>            log(&quot;pushToUpdateToken -&gt; $tokenValue&quot;);<br>            break;<br>        }<br>      },<br>    );<br>  }<br>  //only if you will test via API<br>  static Future&lt;void&gt; requestPushNotificationPermission() async {<br>    try {<br>      await platform.invokeMethod(&quot;requestForNotificationPermission&quot;);<br>    } on PlatformException catch (e) {<br>      throw PlatformException(message: e.message, code: e.code);<br>    }<br>  }<br>  //only if you will test via API<br>  static Future&lt;void&gt; registerDevice() async {<br>    try {<br>      await platform.invokeMethod(&quot;registerDevice&quot;);<br>    } on PlatformException catch (e) {<br>      throw PlatformException(message: e.message, code: e.code);<br>    }<br>  }<br><br>  Future&lt;void&gt; startLiveActivity({required LiveActivityModel data}) async {<br>    try {<br>      await platform.invokeMethod(<br>        &#39;startLiveActivity&#39;,<br>        data.toJson(),<br>      );<br>    } on PlatformException catch (e) {<br>      log(&quot;Failed to start live activity: &#39;${e.message}&#39;.&quot;);<br>    }<br>  }<br><br>  Future&lt;void&gt; updateLiveActivity({required LiveActivityModel data}) async {<br>    try {<br>      await platform.invokeMethod(<br>        &#39;updateLiveActivity&#39;,<br>        data.toJson(),<br>      );<br>    } on PlatformException catch (e) {<br>      log(&quot;Failed to start live activity: &#39;${e.message}&#39;.&quot;);<br>    }<br>  }<br><br>  Future&lt;void&gt; endLiveActivity() async {<br>    try {<br>      await platform.invokeMethod(<br>        &#39;endLiveActivity&#39;,<br>      );<br>    } on PlatformException catch (e) {<br>      log(&quot;Failed to start live activity: &#39;${e.message}&#39;.&quot;);<br>    }<br>  }<br>}</pre><p>Initialize the request to receive push notification, register device and listen to changes in pushToStartToken and pushToUpdateToken. when your flutter app is launched.</p><pre>import &#39;package:flutter/cupertino.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:live_activity_flutter/src/services/live_activity_service.dart&#39;;<br>import &#39;package:live_activity_flutter/src/views/home_view.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br> //only if you will test via API<br>  await LiveActivityService.requestPushNotificationPermission()<br>      .then((value) async {<br>    await LiveActivityService.registerDevice();<br>    await LiveActivityService().listener();<br>  });<br><br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return const CupertinoApp(<br>      title: &#39;Live Activity App&#39;,<br>      theme: CupertinoThemeData(<br>        brightness: Brightness.light,<br>        primaryColor: Colors.pinkAccent,<br>      ),<br>      home: HomeView(),<br>    );<br>  }<br>}</pre><p>To see my implementation check my <a href="https://github.com/MatheusHenriq/Live-Activity-APP">Github Repository</a>.</p><h3>Test live activities locally</h3><p>Test locally consist on call swift methods from flutter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXRHW40Cn1c0bl9-mUeVwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDSa7piYhKmEw5NFPcZ3xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yca2VMaKgojBPoOCNsp4gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUHZrUbN8pZs1wG1YVXWdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHAkh7_oN-wEjRGxdavxuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_n02UZ14X0NmmFJig3O2jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaHbK-2-83clNGPGZx5T_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GevBrcMCVqqqBwcDzmIHcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*838-Se6ijXyeSTyFMyOo9Q.png" /></figure><h3>Test live activities via API</h3><p>To test Live Activities via API, you will need to send a push notification to a specific device using token based connection. To use token based connection you will need to generate a token that contains this type of scruct</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*OpzNsCoC3vc_7HJ17S4VhA.png" /></figure><p>Do you remeber when I ask you to create a key and save it on your computer? now we will use it.</p><p>We have some ways to generate this token, and I will show you two: cloudKit and shell script</p><p>To generate your token via cloudKit:</p><ul><li>Access <a href="https://icloud.developer.apple.com/">CloudKit console</a>.</li><li>Select Push Notification</li><li>Select your app bundleId</li><li>Select Tools</li><li>On private Key select your key .p8</li><li>Get your token on Generated Token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijDBDO7_mJ5deZhiFsxg5A.png" /></figure><p>To generate your token via shell script, create a file.sh and type this code:</p><pre>#!/bin/bash<br>TEAM_ID=&quot;YOUR_TEAM_ID&quot;<br>TOKEN_KEY_FILE_NAME=&quot;path to .p8&quot;<br>AUTH_KEY_ID=&quot;KEY ID&quot;<br>TOPIC=&quot;APP BUNDLE ID&quot;<br>JWT_ISSUE_TIME=$(date +%s)<br>JWT_HEADER=$(printf &#39;{ &quot;alg&quot;: &quot;ES256&quot;, &quot;kid&quot;: &quot;%s&quot; }&#39; &quot;${AUTH_KEY_ID}&quot; | openssl base64 -e -A | tr -- &#39;+/&#39; &#39;-_&#39; | tr -d =)<br>JWT_CLAIMS=$(printf &#39;{ &quot;iss&quot;: &quot;%s&quot;, &quot;iat&quot;: %d }&#39; &quot;${TEAM_ID}&quot; &quot;${JWT_ISSUE_TIME}&quot; | openssl base64 -e -A | tr -- &#39;+/&#39; &#39;-_&#39; | tr -d =)<br>JWT_HEADER_CLAIMS=&quot;${JWT_HEADER}.${JWT_CLAIMS}&quot;<br>JWT_SIGNED_HEADER_CLAIMS=$(printf &quot;${JWT_HEADER_CLAIMS}&quot; | openssl dgst -binary -sha256 -sign &quot;${TOKEN_KEY_FILE_NAME}&quot; | openssl base64 -e -A | tr -- &#39;+/&#39; &#39;-_&#39; | tr -d =)<br>AUTHENTICATION_TOKEN=&quot;${JWT_HEADER}.${JWT_CLAIMS}.${JWT_SIGNED_HEADER_CLAIMS}&quot;<br>echo $AUTHENTICATION_TOKEN<br>echo $JWT_ISSUE_TIME</pre><p>Type sh &lt;filename&gt;.sh on your terminal and you will be able to see the token and timestamp to start, update and end live activities.</p><p>After that you will use this token to make an Bearer Authorization.</p><p>Once we finish that, Access your Postman and put this curl</p><pre>curl --location &#39;https://api.development.push.apple.com:443/3/device/:pushToken&#39; \<br>--header &#39;apns-topic:&lt;YOURBUNDLEID&gt;.push-type.liveactivity&#39; \<br>--header &#39;apns-push-type: liveactivity&#39; \<br>--header &#39;apns-priority: 10&#39; \<br>--header &#39;apns-expiration: 0&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Authorization: Bearer &lt;AUTHENTICATION_TOKEN&gt;&#39; \<br>--data &#39;{<br>    &quot;aps&quot;: {<br>        &quot;timestamp&quot;:1736880549, // YOUR TIMESTAMP HERE<br>        &quot;event&quot;: &quot;update&quot;,<br>        &quot;content-state&quot;: {<br>            &quot;driverCode&quot;: &quot;XJAGHAR4&quot;,<br>            &quot;carModel&quot;: &quot;Corolla&quot;,<br>            &quot;minutesToArrive&quot;: 0,<br>            &quot;carArriveProgress&quot;: 100<br>        }<br>    }<br>}&#39;</pre><p>On your request settings, do not forget to put http version to http/2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTgMjsf06hCjecLg0Z873g.png" /></figure><p>on :pushToken you will put pushToUpdateToken to trigger update and end events, and pushToStartToken to start your live activity.</p><p>Live activities have three types of events:</p><ul><li>start</li><li>update</li><li>end</li></ul><p>the start event can only be trigger via api to iOS versions greater or equal 17.2, devices that have a lower version will have to start live activities when the app is running.</p><p>The request body to start live activity will have these lines:</p><pre><br>{<br>    &quot;aps&quot;: {<br>        &quot;timestamp&quot;:0,<br>        &quot;event&quot;: &quot;start&quot;,<br>        &quot;content-state&quot;: { <br>            &quot;driverCode&quot;: &quot;XJAGHAR4&quot;,<br>            &quot;carModel&quot;: &quot;Corolla&quot;,<br>            &quot;minutesToArrive&quot;: 10,<br>            &quot;carArriveProgress&quot;: 20<br>        },<br>        &quot;input-push-token&quot;: 1, //guarantee that after start an activity, live activity will generate another pushToUpdateToken<br>        &quot;attributes-type&quot;: &quot;LiveActivityWidgetAttributes&quot;, //the name of Live Activity Attribute<br>        &quot;attributes&quot;: {<br>            &quot;driverCode&quot;: &quot;XJAGHAR4&quot;,<br>            &quot;carModel&quot;: &quot;Corolla&quot;,<br>            &quot;minutesToArrive&quot;: 10,<br>            &quot;carArriveProgress&quot;: 20<br>        },<br>    }<br>}</pre><p>The request to update live activity will have these lines:</p><pre>{<br>    &quot;aps&quot;: {<br>        &quot;timestamp&quot;:1736880549, //put here the timestamp that you wanna to trigger this event<br>        &quot;event&quot;: &quot;update&quot;,<br>        &quot;content-state&quot;: {<br>            &quot;driverCode&quot;: &quot;XJAGHAR4&quot;,<br>            &quot;carModel&quot;: &quot;Corolla&quot;,<br>            &quot;minutesToArrive&quot;: 0,<br>            &quot;carArriveProgress&quot;: 100<br>        }<br>    }<br>}<br></pre><p>The request to end live activity will have these lines:</p><pre>{<br>     &quot;aps&quot;: {<br>         &quot;event&quot;: &quot;end&quot;,<br>         &quot;dismissal-date&quot;: 1736427293,//this line tells when your live activity should end<br>         &quot;content-state&quot;: {},<br>         &quot;timestamp&quot;: 1736429348<br>     }<br> }</pre><h3>Conclusion</h3><p>Live Activity is an amazing feature that allows us to display up-to-date information to our users in a fancy way.</p><p>In this article we create live activity, create a manager to handle to all events that live activity have, listen to changes in pushToStartToken and pushToUpdateToken, implement this service on flutter, call events via methodChannel and test locally and in a production scenario.</p><p>Check my <a href="https://github.com/MatheusHenriq/Live-Activity-APP">Github repository</a> to see the source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*NsDVHcAVAde53pbs.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4fcca6325d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live Activity on Flutter Android — An alternative implementation.]]></title>
            <link>https://medium.com/@matheusdeveloper.henrique/live-activity-on-flutter-android-an-alternative-implementation-1e16bec1fbd8?source=rss-f7b76e54cd9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e16bec1fbd8</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[live-activities]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Matheus Henrique de Souza Fontenele]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 23:02:10 GMT</pubDate>
            <atom:updated>2024-09-20T00:12:01.194Z</atom:updated>
            <content:encoded><![CDATA[<h3>Live Activity on Flutter Android — An alternative implementation.</h3><p><em>Hello, in this tutorial we&#39;ll make an alternative implement for live activities on android. It will not look the same because of android limitations, but its a pretty good alternative.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUGIn49VOd6VT_Bq7SrqEQ.png" /></figure><h3>Introduction</h3><p>Live activity is an iOS feature that displays up-to-date information from your app, allowing the user to see the progress of an activity. Unlike iOS, Android does not provide such functionality, but we can simulate the live activity behavior on Android manipulating notifications services with remoteViews.</p><p>In this article I will show you how to implement this service on kotlin and communicate with flutter via methodChannels. By the end of this article you’ll be able to create “Live notifications” that simulate iOS live activity.</p><p><strong>Summary:</strong></p><ul><li>Android Notifications</li><li>RemoteViews</li><li>XML</li><li>Android services implementation</li><li>Flutter service implementation</li><li>Result</li><li>Conclusion</li></ul><h3>Android notifications</h3><p>Android notification is an amazing feature to provide information and keep users engaged.</p><p>From android 8(Oreo), notifications start to be linked by channels. This behavior allows the user to choose which notification channel he/she wants to receive or not. One application can owns many notifications channels. Its importante to set a channel to a notification. otherwise it will not appear on device screen.</p><p>Notifications have an attribute called &quot;importance&quot; with four type of status, with impact on user screen:</p><ul><li>High — Shows heads-up notifications, with sound, vibrate and will be display on user screen .</li><li>default — Has the same behavior of high, but isn&#39;t showed as heads-up notification.</li><li>Low — Only showed on notification tab and doesn’t have sound or vibration.</li></ul><p>When we create a notification, we can add some attributes to personalize it.</p><pre>Notification noti = new Notification.Builder(mContext)<br>         .setContentTitle(&quot;New mail from &quot; + sender.toString())<br>         .setContentText(subject)<br>         .setSmallIcon(R.drawable.new_mail)<br>         .setLargeIcon(aBitmap)<br>         .build();</pre><p>You can see all methods accessing the <a href="https://developer.android.com/reference/android/app/Notification.Builder">documentation</a>. One of this method is setCustomBigContentView that we&#39;ll be use to show the notification content with RemoteViews.</p><h3>RemoteViews</h3><p>RemoteViews is a class that makes possible create and manipulate layout resources.</p><p>It has a range of layouts and widgets that can be used on it. Take a look at the <a href="https://developer.android.com/reference/android/widget/RemoteViews">documentation</a> for more information.</p><p>RemoteViews is declared passing the ApplicationId and layoutid/viewid</p><pre>RemoteViews(&lt;your_application_id&gt;, R.layout.&lt;your layout file&gt;)</pre><p>and has many methods to manipulate layout.</p><p>The RemoteViews will be used to create a personalized view for our notification.</p><h3>XML</h3><p>XML layout file defines a structure of UI. It is composed by a View and GroupView hierarchy. Each view created inside XML can has an ID, that can be used to make reference to this component in other files.</p><p>This XML layout file will be used to inflate out RemoteViews, and with RemoteViews manipulation methods we will change XML views components through view Ids.</p><h3>Android Services implementation</h3><p>Before implementation, lets talk about the app content. Its a delivery app, so we will send the minutes remaining to the delivery arrive and the progress of this delivery to notification.</p><p>When the delivery arrives, we change the notification content.</p><p>We will implement four methods:</p><ul><li>startNotifications — Will start our notification service</li><li>updateNotifications — Will update our notification content</li><li>endNotifications — Will finish our notification service and dispose all notifications from user screen that is linked to our notificationChannel</li><li>finishDeliveryNotification — Will display a different notification that will be appear when the delivery arrives.</li></ul><pre>package com.example.android_live_notification<br><br>class MainActivity: FlutterActivity() {<br><br>    private val permissions = if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>        arrayOf(Manifest.permission.POST_NOTIFICATIONS)<br>    } else {<br>        arrayOf()<br>    }<br>    private val flutterChannel = &quot;androidInteractiveNotifications&quot;<br>    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br>        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, flutterChannel).setMethodCallHandler {<br>                call, result -&gt;<br>            if (call.method == &quot;startNotifications&quot;) {<br>                if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>                    val args = call.arguments&lt;Map&lt;String, Any&gt;&gt;()<br>                    val progress = args?.get(&quot;progress&quot;) as? Int<br>                    val minutes = args?.get(&quot;minutesToDelivery&quot;) as? Int<br><br>                    if( progress != null &amp;&amp; minutes != null){<br>                        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>                            LiveNotificationManager(context).showNotification(progress,minutes)<br>                        }<br>                    }<br>                }<br>                result.success(&quot;Notification displayed&quot;)<br>            }<br>            else if (call.method == &quot;updateNotifications&quot;) {<br>                if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>                    val args = call.arguments&lt;Map&lt;String, Any&gt;&gt;()<br>                    val progress = args?.get(&quot;progress&quot;) as? Int<br>                    val minutes = args?.get(&quot;minutesToDelivery&quot;) as? Int<br>                    if(progress != null &amp;&amp; minutes != null){<br>                        LiveNotificationManager(context)<br>                            .updateNotification(currentProgress =  progress, minutesToDelivery = minutes)<br>                    }<br>                }<br>            }<br>            else if (call.method == &quot;finishDeliveryNotification&quot;) {<br>                if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>                    LiveNotificationManager(context)<br>                        .finishDeliveryNotification()<br>                }<br>                result.success(&quot;Notification delivered&quot;)<br>            }<br>            else if (call.method == &quot;endNotifications&quot;) {<br>                if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>                    LiveNotificationManager(context)<br>                        .endNotification()<br>                }<br>                result.success(&quot;Notification cancelled&quot;)<br>            }<br>        }<br>    }<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>            ActivityCompat.requestPermissions(this, permissions, 200)<br>        }<br>    }<br><br>    override fun onStop() {<br>        super.onStop()<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>            LiveNotificationManager(context).endNotification()<br>        }<br>    }<br>}</pre><p>We call requestPermissions when the app is launched. When the app is closed we stop our notification service because we only manipulate data when the app is alive(on background or foreground).</p><p>After that, we need to implement a class that will manage notifications.</p><pre><br>package com.example.android_live_notification<br><br>@RequiresApi(Build.VERSION_CODES.O)<br>class LiveNotificationManager(private val context: Context)  {<br>    private val remoteViews = RemoteViews(&quot;com.example.android_live_notification&quot;, R.layout.live_notification)<br>    private val  channelWithHighPriority = &quot;channelWithHighPriority&quot;<br>    private val  channelWithDefaultPriority = &quot;channelWithDefaultPriority&quot;<br>    private val  notificationId = 100<br>    private val pendingIntent = PendingIntent.getActivity(<br>        context,<br>        200,<br>        Intent(context, MainActivity::class.java).apply {<br>            flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT<br>        },<br>        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE<br>    )<br>    private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager<br>    init {<br>       createNotificationChannel(channelWithDefaultPriority)<br>        createNotificationChannel(channelWithHighPriority, importanceHigh = true)<br>    }<br><br><br>    private fun createNotificationChannel(channelName : String, importanceHigh : Boolean = false) {<br>        val importance = if (importanceHigh) IMPORTANCE_HIGH else IMPORTANCE_DEFAULT<br>        val existingChannel =  (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).getNotificationChannel(channelName)<br>         if(existingChannel == null){<br>            val channel =<br>                NotificationChannel(channelName, &quot;App Delivery Notification&quot;, importance).apply {<br>                    setSound(null, null)<br>                    vibrationPattern = longArrayOf(0L)<br>                }<br><br>            notificationManager.createNotificationChannel(channel)<br>        }<br>    }<br>   private fun onFirstNotification( minutesToDelivery: Int ) : Notification{<br>        val minuteString = if  (minutesToDelivery &gt; 1 ) &quot;minutes&quot; else &quot;minute&quot;<br>        return  Notification.Builder(context, channelWithHighPriority)<br>            .setSmallIcon(R.drawable.notification_icon)<br>            .setContentTitle(&quot;Live Notification - Delivery out for shipment&quot;)<br>            .setContentIntent(pendingIntent)<br>            .setWhen(3000)<br>            .setContentText(&quot;Your delivery comes in $minutesToDelivery $minuteString&quot;)<br>            .setCustomBigContentView(remoteViews)<br>            .build()<br>    }<br><br>    private fun onGoingNotification(minutesToDelivery: Int ) : Notification{<br>        val minuteString = if  (minutesToDelivery &gt; 1 ) &quot;minutes&quot; else &quot;minute&quot;<br>        return  Notification.Builder(context, channelWithDefaultPriority)<br>            .setSmallIcon(R.drawable.notification_icon)<br>            .setOngoing(true)<br>            .setContentTitle(&quot;Live Notification - Delivery on the way&quot;)<br>            .setContentIntent(pendingIntent)<br>            .setContentText(&quot;Your delivery comes in $minutesToDelivery $minuteString&quot;)<br>            .setCustomBigContentView(remoteViews)<br>            .build()<br>    }<br><br>    private fun onFinishNotification() : Notification{3<br>        return Notification.Builder(context,channelWithHighPriority)<br>            .setSmallIcon(R.drawable.notification_icon)<br>            .setContentIntent(pendingIntent)<br>            .setAutoCancel(true)<br>            .setContentTitle(&quot;Live Notification - Arrives&quot;)<br>            .setContentText(&quot;Your delivery arrive&quot;)<br>            .setCustomBigContentView(remoteViews)<br>            .build()<br>    }<br><br>    fun showNotification(currentProgress: Int, minutesToDelivery: Int)  {<br><br>        val minuteString = if  (minutesToDelivery &gt; 1 ) &quot;minutes&quot; else &quot;minute&quot;<br>        val notification = onFirstNotification(minutesToDelivery)<br>        remoteViews.setTextViewText(R.id.minutes_to_delivery, &quot;$minutesToDelivery $minuteString&quot;)<br>        remoteViews.setTextViewText(R.id.progress_text, &quot;$currentProgress%&quot;)<br>        remoteViews.setProgressBar(R.id.progress,100,currentProgress,false)<br>        notificationManager.notify(notificationId, notification)<br>    }<br><br>    fun updateNotification(currentProgress: Int,minutesToDelivery: Int) {<br>        val notification =  onGoingNotification(minutesToDelivery)<br>        val minuteString = if  (minutesToDelivery &gt; 1 ) &quot;minutes&quot; else &quot;minute&quot;<br>        remoteViews.setTextViewText(R.id.minutes_to_delivery, &quot;$minutesToDelivery $minuteString&quot;)<br>        remoteViews.setTextViewText(R.id.progress_text, &quot;$currentProgress%&quot;)<br>        remoteViews.setProgressBar(R.id.progress,100,currentProgress,false)<br>        notificationManager.notify(notificationId, notification)<br>    }<br><br><br>    fun finishDeliveryNotification() {<br><br>        val notification = onFinishNotification()<br>        remoteViews.setTextViewText(R.id.delivery_message, &quot;Your delivery Arrive&quot;)<br>        remoteViews.setImageViewResource(R.id.image,R.drawable.delivery_arrive)<br>        remoteViews.setViewVisibility(R.id.progress, View.GONE)<br>        remoteViews.setViewVisibility(R.id.progress_text, View.GONE)<br>        remoteViews.setViewVisibility(R.id.minutes_to_delivery, View.GONE)<br>        remoteViews.setTextViewText(R.id.delivery_subtitle,&quot;Enjoy your delivery :)&quot;)<br>        notificationManager.notify(notificationId, notification)<br>    }<br><br>    fun endNotification() {<br>      val notificationManager =   context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager<br>        notificationManager.deleteNotificationChannel(channelWithHighPriority)<br>        notificationManager.deleteNotificationChannel(channelWithDefaultPriority)<br>        remoteViews.setTextViewText(R.id.delivery_message, &quot;Delivering in &quot;)<br>        remoteViews.setTextViewText(R.id.delivery_subtitle,&quot;Your delivery is coming&quot;)<br>        remoteViews.setViewVisibility(R.id.progress, View.VISIBLE)<br>        remoteViews.setViewVisibility(R.id.progress_text, View.VISIBLE)<br>        remoteViews.setViewVisibility(R.id.minutes_to_delivery, View.VISIBLE)<br>        remoteViews.setImageViewResource(R.id.image,R.drawable.delivery1)<br>    }<br>}<br></pre><p>Note that the views that we want to change has the parameter id, that will be retrieve on RemoteView to change the content.</p><h3>Flutter service implementation</h3><pre>import &#39;package:android_live_notification/src/model/live_notification_model.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br><br>class LiveNotificationService {<br>  final MethodChannel _method = const MethodChannel(&quot;androidInteractiveNotifications&quot;);<br><br>  Future&lt;void&gt; startNotifications({required LiveNotificationModel data}) async {<br>    try {<br>      await _method.invokeMethod(&quot;startNotifications&quot;, data.toJson());<br>    } on PlatformException catch (e) {<br>      throw PlatformException(code: e.code);<br>    }<br>  }<br><br>  Future&lt;void&gt; updateNotifications({required LiveNotificationModel data}) async {<br>    try {<br>      await _method.invokeMethod(&quot;updateNotifications&quot;, data.toJson());<br>    } on PlatformException catch (e) {<br>      throw PlatformException(code: e.code);<br>    }<br>  }<br><br>  Future&lt;void&gt; finishDeliveryNotification() async {<br>    try {<br>      await _method.invokeMethod(&quot;finishDeliveryNotification&quot;);<br>    } on PlatformException catch (e) {<br>      throw PlatformException(code: e.code);<br>    }<br>  }<br><br>  Future&lt;void&gt; endNotifications() async {<br>    try {<br>      await _method.invokeMethod(&quot;endNotifications&quot;);<br>    } on PlatformException catch (e) {<br>      throw PlatformException(code: e.code);<br>    }<br>  }<br>}</pre><h3><strong>Result</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*AwPJKwmfTTLevzdlVtc2Ow.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*y64IkNCL1kXP-ERHVyAFIA.gif" /></figure><h3>Conclusion</h3><p>Notifications are an amazing feature to provide information and keep the user engaged. Displaying up-to-date information is important when you want to show users the update about some activity that starts on the app.</p><p>In this tutorial we build the behavior of LiveActivity from iOS on Android using notifications and RemoteViews.</p><p>Check my <a href="https://github.com/MatheusHenriq/Flutter-android-Live-Notification">Github repository</a> to see the source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*y_bQZBZD5KaNsEAl.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e16bec1fbd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apple push notifications Service(APNS) in Flutter iOS.]]></title>
            <link>https://medium.com/@matheusdeveloper.henrique/apple-push-notifications-service-apns-in-flutter-ios-d673221ebb03?source=rss-f7b76e54cd9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d673221ebb03</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Matheus Henrique de Souza Fontenele]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 16:01:32 GMT</pubDate>
            <atom:updated>2024-09-09T19:16:27.468Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello, in this tutorial we will talk about how to setup push notifications on your iOS flutter app, without using firebase, one signal or other third-party service.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDdiU9cbZlOKAazLigt40w.png" /></figure><p><strong>Introduction</strong></p><p>Firebase and OneSignal are the most common services to deal with push notifications in flutter. Furthermore, when your backend use the Apple API to trigger push notifications, using other services will not help to solve this problem. In this scenario, the best way is implement natively the handler of push notifications on swift and setup the flutter communication with this service.</p><p><strong>Summary</strong></p><ul><li>Understanding APNS</li><li>Setting up Xcode.</li><li>Setting Up Certificate and identifier(need to be part of a development team).</li><li>Swift implementation.</li><li>Handle push notifications.</li><li>Flutter implementation.</li><li>Test push notifications simulation backend via cloudKit(need to be part of an enterprise team).</li><li>Test push notification locally(no need to be part of an enterprise team).</li><li>Conclusion</li></ul><h3>Understanding APNS</h3><p>Apple push notification service is the official apple service to deliver push notifications for iOS devices when the app is in foreground, background or closed.</p><p>To APNS work app needs to:</p><ul><li>Have push notification permission accepted by the user.</li><li>Register device to receive push notifications.</li><li>Send to the backend the device token used to trigger a notification to the specific device.</li></ul><h3>Setting up Xcode and Apple</h3><p>In Xcode, open xcworkspace from your flutter project, click on Runner -&gt; Signing &amp; Capabilities and add Push Notification and Background Modes-&gt;Remote Notification. This respective capabilites will let your app receive push notifications when your app is alive and when its closed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upMLleCuSMwxqsQU89B5pQ.png" /></figure><h3>Setting up Certificates and Identifier</h3><p>After that, Access <a href="https://developer.apple.com/account/resources">Certificate, Identifiers and profiles</a> and create an identifier for your app(with the same bundleId from your flutter app, obviously) and enables Push notifications.</p><p>Next, go to Certificates option and create an Apple Push Notification service SSL (Sandbox) or Apple Push Notification service SSL (Sandbox &amp; Production) and link it to the app identifier that you created.</p><p>Afterwards, we finish our apple setup and we can dive into the code.</p><h3>Swift Implementation</h3><p>Go to ios/runner/AppDelegate and import the UserNotifications library.</p><pre>import UserNotifications</pre><p>After that, inside application function, implement the FlutterMethodChannel with three methods:</p><ul><li>requestNotificationPermissions to request to user if app can send push notifications.</li><li>registerForPushNotifications to register our app to receive push notifications.</li><li>retrieveDeviceToken to get the device token, that we will use to send to the api to receive push notifications.</li></ul><pre>    let channelName : String = &quot;PushNotificationChannel&quot;<br>    var deviceToken : String = &quot;&quot;<br><br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        <br>        <br>        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController<br>        let pushNotificationChannel = FlutterMethodChannel(name: channelName, binaryMessenger: controller.binaryMessenger)<br>        <br>        if #available(iOS 10.0, *) {<br>        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate<br>        }<br><br>        pushNotificationChannel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in<br>            switch call.method {<br>            case &quot;requestNotificationPermissions&quot;:<br>                self?.requestNotificationPermissions(result: result)<br>            case &quot;registerForPushNotifications&quot;:<br>                self?.registerForPushNotifications(application: application, result: result)<br>            case &quot;retrieveDeviceToken&quot;:<br>                self?.getDeviceToken(result: result)        <br>            default:<br>                result(FlutterMethodNotImplemented)<br>            }<br>        }<br>        <br>        GeneratedPluginRegistrant.register(with: self)<br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }</pre><p>Next step is to define this three methods:</p><pre> private func requestNotificationPermissions(result: @escaping FlutterResult) {<br>        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in<br>        if let error = error {<br>            result(FlutterError(code: &quot;PERMISSION_ERROR&quot;, message: &quot;Failed to request permissions&quot;, details: error.localizedDescription))<br>            return<br>        }<br>            result(granted)<br>        }<br>    }<br><br>    private func registerForPushNotifications(application: UIApplication, result: @escaping FlutterResult) {<br>        application.registerForRemoteNotifications()<br>        result(&quot;Device Token registration initiated&quot;)<br>    }<br>    <br>    private func getDeviceToken(result: @escaping FlutterResult) {<br>        if(deviceToken.isEmpty){<br>            result(FlutterError(code: &quot;UNAVAILABLE&quot;, message: &quot;Device token not available&quot;, details: nil))<br>        } else{<br>            result(deviceToken)<br>        }<br>    }</pre><p>The device token will be set after the registerForPushNotifications being called, for that, we will need to implement this with this function:</p><pre> override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {<br>        let tokenParts = deviceToken.map { data in String(format: &quot;%02.2hhx&quot;, data) }<br>        let token = tokenParts.joined()<br>        self.deviceToken = token<br>    }</pre><p>We need to use this map to convert the Data object in hexadecimal string. This string will be the device token, and this device token will be the device identifier to receive push notifications.</p><p>We use the overrided function application because this application is the function that listened to every life time event in our ios application. So when we register our device, this application listen to this and get the device token for us.</p><h3>Handle Push Notifications</h3><p>When we import the UserNotifications library, we will be able to override the userNotificationCenter, and this method will handle the push notification when our app is in foreground mode.</p><pre>override func userNotificationCenter(_ center: UNUserNotificationCenter,<br>                                 willPresent notification: UNNotification,<br>                                 withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void) {        <br>        if #available(iOS 14.0, *) {<br>            completionHandler([.banner, .list, .sound, .badge])<br>         } else {<br>             completionHandler([.alert, .sound, .badge])<br>         }<br>     }<br>    <br>   override func userNotificationCenter(_ center: UNUserNotificationCenter,<br>                                didReceive response: UNNotificationResponse,<br>                                withCompletionHandler completionHandler: @escaping () -&gt; Void) {<br>        let userInfo = response.notification.request.content.userInfo<br>        handleNotification(userInfo: userInfo)<br>        completionHandler()<br>    }<br><br>private func handleNotification(userInfo: [AnyHashable: Any]) {<br>        let controller: FlutterViewController = window?.rootViewController as! FlutterViewController<br>        let pushNotificationChannel = FlutterMethodChannel(name: channelName,binaryMessenger: controller.binaryMessenger)<br>        if let customData = userInfo[&quot;customKey&quot;] as? String {<br>            pushNotificationChannel.invokeMethod(&quot;onPushNotification&quot;, arguments: customData)<br>        }<br>    }</pre><p>Notice that in iOS 14 and greater versions, we cannot use [.alert, .sound, .badge]. Instead of it, we use [.banner, .list, .sound, .badge]. The .list and .banner together have the same effect as .alert. I think the apple team does this to give more granular access to the developers.</p><ul><li>.banner: show the notification as a banner on the top of the screen (iOS 14+).</li><li>.list: show the notification on the notification center (iOS 14+).</li><li>.sound: Plays the notification sound.</li><li>.badge: update the app icon with a number in badge.</li><li>.alert:shows visual alert(before iOS 14).</li></ul><p>We have two methods with userNotificationCenter, but if you notice they have different behaviors. The first is willPresent and the other is didReceive. The main difference is:</p><ul><li>willPresent = shows the notification on the user screen</li><li>didReceive = after receive, will trigger some other function that we want.</li></ul><p>In our case, after receiving a push notification, if you click on it, it will trigger the handleNotification method. This method will send the customKey to our flutter code. After that, the setup is concluded.</p><h3>Flutter implementation</h3><p>create an service to handler the notification.</p><pre>import &#39;package:flutter/cupertino.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br><br>class PushNotificationService {<br>  static const String _channelName = &quot;PushNotificationChannel&quot;;<br><br>  static const MethodChannel _channel = MethodChannel(_channelName);<br><br>  static Future&lt;void&gt; requestPushNotificationPermission() async {<br>    try {<br>      await _channel.invokeMethod(&quot;requestNotificationPermissions&quot;);<br>    } on PlatformException catch (e) {<br>      throw PlatformException(message: e.message, code: e.code);<br>    }<br>  }<br><br>  static Future&lt;void&gt; registerDevice() async {<br>    try {<br>      await _channel.invokeMethod(&quot;registerForPushNotifications&quot;);<br>    } on PlatformException catch (e) {<br>      throw PlatformException(message: e.message, code: e.code);<br>    }<br>  }<br><br>  static Future&lt;String?&gt; retriveDeviceToken() async {<br>    try {<br>      return await _channel.invokeMethod&lt;String&gt;(&quot;retrieveDeviceToken&quot;);<br>    } on PlatformException catch (e) {<br>      throw PlatformException(message: e.message, code: e.code);<br>    }<br>  }<br><br>  static handlerPushNotificationData({required BuildContext context}) async {<br>    _channel.setMethodCallHandler((call) async {<br>      if (call.method == &quot;onPushNotification&quot;) {<br>        final customKey = call.arguments as String;<br>        showCupertinoDialog&lt;void&gt;(<br>          context: context,<br>          builder: (BuildContext context) =&gt; CupertinoAlertDialog(<br>            title: const Text(&#39;You click on Push Notification&#39;),<br>            content: Text(&#39;The text is -&gt; $customKey&#39;),<br>            actions: &lt;CupertinoDialogAction&gt;[<br>              CupertinoDialogAction(<br>                onPressed: () {<br>                  Navigator.pop(context);<br>                },<br>                child: const Text(&#39;Close&#39;),<br>              ),<br>            ],<br>          ),<br>        );<br>      }<br>    });<br>  }<br>}<br></pre><p>Initialize the request and register device when your flutter app is launched.</p><pre>import &#39;package:flutter/cupertino.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:push_notificiation_example/src/services/push_notification_service.dart&#39;;<br>import &#39;package:push_notificiation_example/src/views/home_view.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await PushNotificationService.requestPushNotificationPermission().then((value) async {<br>    await PushNotificationService.registerDevice();<br>  });<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return const CupertinoApp(<br>      title: &#39;Push Notification&#39;,<br>      theme: CupertinoThemeData(brightness: Brightness.light, primaryColor: Colors.pinkAccent),<br>      home: HomeView(),<br>    );<br>  }<br>}</pre><p>The rest of the flutter code I will let to your imagination. To see my implementation check my <a href="https://github.com/MatheusHenriq/PushNotificationFlutteriOS">Github Repository</a>.</p><h3>Test push notifications simulation backend via cloudKit</h3><p>Follow this steps:</p><ul><li>Access <a href="https://icloud.developer.apple.com/">CloudKit console</a>.</li><li>Select push notifications.</li><li>Be aware about the correct development team on the top right corner.</li><li>Select your app bundleId on the top left corner.</li><li>Choose option send.</li><li>Create a notification clicking on the last icon next to notification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwlRvFhx6KwLfYCLcpPXVA.png" /></figure><p>After that, give a name to the push notification and on the &quot;Send notification to device&quot; put your device token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7SOneeLG2Xqg1eIGo6lXw.png" /></figure><p>Next, go to the bottom of the page, and add the text that you want in title, subtitle and body.</p><p>I create a customKey clicking on the last &quot;+ Add Item&quot;, I named this item customKey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m92_wd1LRJ8oul0WR0vWlA.png" /></figure><p>Click on send button on the top right corner of the page and see the magic on your device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Hq2adRLxDIlzVwFcDT_3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8NZmU2Koj6P0OxPzkbYrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2R58zBbyNpUffGpwYrDBw.png" /></figure><h3>Test push notification locally</h3><p>First, you need to create an apns file on ios/runner file, click on new file, and create an empty file and put &lt;file_name&gt;.apns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7I-QLPeLr1fS5oxxCAKGw.png" /></figure><p>Inside this file, put this code:</p><pre>{<br>  &quot;Simulator Target Bundle&quot;: &quot;com.example.pushNotificiationExample&quot;, //your bundleId<br>  &quot;aps&quot;: {<br>    &quot;alert&quot;: {<br>      &quot;title&quot;: &quot;Local push notification&quot;,<br>      &quot;subtitle&quot;: &quot;Its a local flutter iOS notification&quot;,<br>      &quot;body&quot;: &quot;I hope it work for you&quot;<br>    },<br>    &quot;badge&quot;: 1,<br>    &quot;sound&quot;: &quot;default&quot;<br>  },<br>  &quot;customKey&quot;: &quot;something nice here - local notification&quot;<br>}</pre><p>after that, type &quot;flutter devices&quot; and get your device id. Next go to ios/runner and type &quot;xcrun simctl push &lt;device_id&gt; &lt;file_name&gt;.apns&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WO-7HTOBMUelZX47QsvZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMYWpBSoOut8nl9GUKcmpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cv_RWWqTL7jSm8s9ld5ulg.png" /></figure><h3>Conclusion</h3><p>Push notifications are one of the most relevant features that your app can provide to keep users aware about news in your app.</p><p>In this article we make the swift implementation of the push notification service and the communication with flutter via method channel. Furthermore we cover how to setup your app to receive this notification on local or in a production scenario.</p><p>Check my G<a href="https://github.com/MatheusHenriq/PushNotificationFlutteriOS">ithub repository</a> to see the source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*qEff258ljPw8af69.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d673221ebb03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter integration test with Gcloud, Firebase Testlab and GitHub Actions]]></title>
            <link>https://medium.com/@matheusdeveloper.henrique/flutter-integration-test-with-gcloud-firebase-testlab-and-github-actions-31ba1f2c173c?source=rss-f7b76e54cd9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31ba1f2c173c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[g-cloud]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Matheus Henrique de Souza Fontenele]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 15:56:05 GMT</pubDate>
            <atom:updated>2024-04-07T19:47:33.377Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter integration test with gcloud, firebase testlab and GitHub Actions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*VJrg1SN1tCxccsIPXwksjA.jpeg" /></figure><p>Hi guys, by the end of this article you’ll be able to create a pipeline to send android/iOS integration tests to Firebase TestLab. So let’s get to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*M3-SHBMWOhLJ1aLgMSBCkg.gif" /></figure><p>To be more organized, let’s talk about these topics in sequence.</p><ol><li>Integration tests</li><li>Firebase</li><li>Gcloud</li><li>Pipeline (Github Actions)</li><li>Conclusion</li></ol><h3>1. Integration Test</h3><p>Integration testing is a stage in software development where components are tested together. It is usually carried out after unit testing and widget testing (in the flutter context).</p><p>It is the last stage because the idea is to test how all the components work together to perform a given purpose.</p><p>As an example, we can imagine an authentication flow, in which the tests would have the following responsibilities:</p><p>Unit tests (functions):</p><ul><li>Testing API returns</li><li>Testing correct authentication flows</li><li>Testing cases of authentication failure</li></ul><p>Widgets (components):</p><ul><li>Test the functioning of the buttons</li><li>Test responsiveness based on page state changes.</li></ul><p>Integration:</p><ul><li>Test the operation of combined functionalities.</li><li>Check that the application is able to carry out a flow without errors.</li></ul><p>Integration tests are guided by keys. This key will make a link to that specific widget and with it we can:</p><ul><li>Check which widget we are in</li><li>Check if the current page has that widget</li><li>Click on a button.</li><li>Navigate to another screen</li><li>Write in a text field</li></ul><p>To carry out the integration tests we need to create a folder in the root directory of the flutter project called integration_test and inside this folder create our test file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvDFsbFZTOcYKJtOlEDhcA.png" /></figure><h3>2. Firebase</h3><p>Firebase is a set of cloud services provided by Google. Firebase and Flutter have a very fluid compatibility as they are both technologies developed by the Google team.</p><p>Among the various services provided by Firebase, the one we’re going to cover in the article is TestLab.</p><p>Testlab can only be used when there is an active project in Firebase.</p><h3>2.1: Creating a project in firebase</h3><p>To create a project in firebase, go to the firebase page <a href="https://firebase.google.com/?hl=pt-br">here</a>, and click on Go to console.</p><p>On this page, click on add project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bum3w3Noi_CbVHMMF7DAUQ.png" /></figure><p>After that you can create your android and ios app, with the respective applicationId and bundleId. Doing this manually can be cumbersome.<br>Flutter has excellent integration with firebase, allowing us, for example, to create applications in a firebase project via command lines using flutterfire.</p><p>FlutterFire is a set of plugins that connect flutter and firebase.</p><p>To install firebase on your machine, use the command</p><pre>npm install firebase-tools -g</pre><p>Then navigate to your flutter project and run the commands</p><pre>export PATH=&quot;$PATH&quot;:&quot;$(DartToolPath)&quot;<br>dart pub global activate flutterfire_cli</pre><p>Once flutterfire_cli is installed, use the command to create the direct applications in the project account you created.</p><pre>export PATH=&quot;$PATH&quot;:&quot;$(DartToolPath)&quot;<br>export PATH=&quot;$PATH&quot;:&quot;$HOME/.pub-cache/bin&quot;</pre><pre>flutterfire configure \<br>--project=&lt;firebase_project_id&gt; \ #Project Id(When you access the firebase page, the name of your project will appear, along with the id associated with it).<br>--platforms=android,ios \ #Platform that will be used in the app<br>--android-package-name=&lt;applicationId&gt; \ -&gt; aplicationID<br>--ios-bundle-id=&lt;BundleId&gt; \ --bundleId <br>-y --token=&lt;FIREBASE_TOKEN&gt;</pre><p>To capture the firebase token, use the command</p><pre>firebase login:ci</pre><p>It will redirect you to your google accounts. By accessing the account you used to create the project in firebase and accepting the terms, you will receive the token in the terminal in which you sent the firebase login:ci command.</p><p>It’s important to remember that this token is for your account, i.e. it works for all projects that have already been created and will be created, so keep it safe.</p><p>NOTE: It can be complicated to execute all these commands one at a time. If you want to execute them all at once, an interesting approach is to create a .sh file, give it permission to execute and place these commands inside the file.</p><p>An example of this would be to place these last commands containing the export up to -y — token inside a file called, for example, create_firebase_projs.sh and give the command chmod +x create_firebase_projs.sh. This command gives you permission to execute the file.</p><p>To run this command, go to the directory where it is located and type ./create_firebase_projs.sh into the terminal.</p><h3>2.2 TestLab</h3><p>TestLab is an application testing infrastructure that relies on the cloud to make x number of devices and configurations available for integration testing. It uses Google’s data center to generate a device and test the application.</p><p>It offers 4 types of tests:</p><ul><li>Instrumentation testing — Android</li><li>Robot test — Android</li><li>Loop testing for games — Android/iOS</li><li>XCTest — iOS.</li></ul><p>We will use 2 types of tests. For android, we’ll use the instrumentation test and for iOS the XCTest.</p><p>Firebase testlab uses 3 concepts:</p><p>Device</p><ul><li>This stage refers to the choice of device to be used in the test. This test takes into account whether the device is a smartphone, tablet or wearable device. These devices are identified by model, OS version, screen orientation (portrait, landscape) and location.</li></ul><p>Testing, test execution</p><ul><li>This is basically the set of tests carried out on a selected device. There is the possibility of testing per device or fragmenting the test and running it on different devices (depending on how many devices you choose to run the test on).</li></ul><p>Test matrix</p><ul><li>This shows the results of the tests carried out on the selected devices. It is important to remember that if you choose N test devices and the test fails on one of them, the entire matrix will receive a failure flag and will be interrupted.</li></ul><p>In short, just follow the rule <strong>Device × Test Execution= Test Matrix</strong></p><h3>2.3 Instrumentation Test — Android Configuration</h3><p>To use the android instrumentation test, you need to add certain settings to the android project.</p><p>The first is to access the android/app/src folder and create the androidTest file.</p><p>Let’s take into account that our project has the following applicationId -&gt; com.example.integrationtest</p><p>When we create the androidTest folder, we also create the java/com/example/integrationtest folders.</p><p>In this last folder, we created a file called MainActivityTest.java (you can name it whatever you like).</p><p>Therefore, the total path will be -&gt;android/app/src/androidTest/java/com/example/integrationtest/MainActivityTest.java</p><p>In this java file, put the following code snippet:</p><pre>package com.example.integrationtest;</pre><pre>import androidx.test.rule.ActivityTestRule;<br>import dev.flutter.plugins.integration_test.FlutterTestRunner;<br>import org.junit.Rule;<br>import org.junit.runner.RunWith;@RunWith(FlutterTestRunner.class)<br>public class MainActivityTest {<br>  @Rule<br>  public ActivityTestRule&lt;MainActivity&gt; rule = new ActivityTestRule&lt;&gt;(MainActivity.class, true, false);<br>}</pre><p>Then, in the android/app/build.gradle folder, add the commands:</p><pre>android {<br>  ...<br>  defaultConfig {<br>    ...<br>    testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>  }<br>}</pre><pre>dependencies {<br>    testImplementation &#39;junit:junit:4.12&#39;    // https://developer.android.com/jetpack/androidx/releases/test/#1.2.0<br>    androidTestImplementation &#39;androidx.test:runner:1.2.0&#39;<br>    androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.2.0&#39;<br>}</pre><p>Once you have completed these steps, you are ready to generate an instrumentation test for android.</p><p>To generate an instrumentation test, use the following commands</p><pre>pushd android<br># flutter build generates files in android/ for building the app<br>flutter build apk<br>./gradlew app:assembleAndroidTest<br>./gradlew app:assembleDebug -Ptarget=&lt;path_to_test&gt;.dart<br>popd</pre><p>Or if you prefer, create a file with this information and run it.</p><p>Here’s an example:<br>Create a file called android_integrationTest.sh(name is up to you).<br>Then use the command chmod +x android_integrationTest.sh</p><p>The chmod +x command gives the specified file permission to execute and authorize.</p><p>Inside android_integrationTest.sh, place the last commands written above.</p><p>To run everything automatically, just type ./android_integrationTest.sh in the directory where the file was created.</p><p>When you send these commands, the test apk will be created in the build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk folder and the release apk in the build/app/outputs/apk/release/app-release.apk folder.</p><p>These two apks can be used to run the test manually by clicking <a href="https://console.firebase.google.com/u/2/project/integration-test-f/testlab/run/instrumentation">here</a></p><h3>2.4 Creating XCTEST on iOS</h3><p>To use XCTEST on iOS, you need to add certain settings to the iOS project.</p><p>The first is to create a RunnerTests file inside the iOS folder. However, this must be done via XCode &gt; File &gt; New &gt; Target. Then filter for the Unit Testing Bundle option and create a target called RunnerTests with the Obj-C language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cug7kDfI8ehkYNAtTIDPJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVpEBOwwxTrodWk9KKEAWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2uHtVWARbaT4py1VNzfVQ.png" /></figure><p>Once the target has been created, a folder called RunnerTests will appear inside the ios folder (ios/RunnerTests/RunnerTests.m).</p><p>Delete the content inside RunnerTests.m and insert the code:</p><pre>@import XCTest;<br>@import integration_test;<br>INTEGRATION_TEST_IOS_RUNNER(RunnerTests)</pre><p>The next step is to access the Podfile inside the ios folder and add the commands:</p><pre>Target &#39;Runner&#39; do<br>  # Do not change existing lines.<br>target &#39;RunnerTests&#39; do <br>    inherit! :search_paths<br>  end<br>end</pre><p>Once finished, the setup for XCTEST is ready to be used.</p><p>The process to follow is similar to the one we used for testing Android instrumentation.</p><p>The file created for testing must contain the following commandss</p><pre>output=&quot;../build/ios_integ&quot;<br>product=&quot;build/ios_integ/Build/Products&quot;</pre><pre># Pass --simulator if building for the simulator.<br>flutter build ios integration_test/&lt;integration_test_file&gt; --releasepushd ios<br>xcodebuild build-for-testing \<br>  -workspace Runner.xcworkspace \<br>  -scheme Runner \<br>  -xcconfig Flutter/Release.xcconfig \<br>  -configuration Release \<br>  -derivedDataPath \<br>  $output -sdk iphoneos<br>popdpushd $product<br>find . -name &quot;Runner_*.xctestrun&quot; -exec zip -r --must-match &quot;ios_tests.zip&quot; &quot;Release-iphoneos&quot; {} +<br>popd</pre><p>A zip file will then be created in the ios/build/ios_integ/Build/Products folder folder named ios_test.zip</p><p>You can use this file to perform the test by clicking <a href="https://console.firebase.google.com/u/2/project/integration-test-f/testlab/run/xctest">here</a>.</p><h3>3. Gcloud</h3><p>Manually uploading files to be tested is an interesting solution when you don’t have the possibility of uploading everything at once via commands. This is not the case; with Gcloud it is possible.</p><p>Gcloud is, in short, a set of physical and virtual resources located in Google’s data centers all over the world. It has a range of services that can be accessed by clicking <a href="https://cloud.google.com/products?hl=pt-br">here</a>.</p><p>We’re going to use the Gcloud CLI, which is a set of tools for creating and managing Google Cloud resources. These services are used to run automation scripts, among other things.</p><h3>3.1 — Utilização da Gcloud CLI</h3><p>The first step to using gCloud is to install it on your machine. You can install it by clicking <a href="https://cloud.google.com/sdk/docs/install?hl=pt-br">here</a>.</p><p>Once Gcloud has been installed, the next step is to apply your project id and a specification file to the gcloud settings.</p><p>To specify the project, use the command</p><pre>gcloud config set project &lt;firebase_project_id&gt;</pre><p>Another key point is when we want to link Gcloud to our firebase project to allow full use of the tool. To do this, you need a configuration file for the firebase project and set the file in gcloud.</p><p>The command to do this is:</p><pre>gcloud auth activate-service-account --key-file=&quot;../&lt;gcloud_config_for_firebase_project.json&gt;&quot;</pre><p>To get this file, you need to create it and download it.</p><p>To create it, go to the gcloud console page <a href="https://console.cloud.google.com/welcome?hl=pt-br">here</a>.</p><p>It is important that the access profile is the same as the one you used to create the project in firebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YD4TlfzNooHk-MeIauJqgg.png" /></figure><p>Next to Google Cloud, in the top left corner, you’ll find your firebase projects, select the project you want to use.</p><p>Then click on IAM and administrator, click on the menu at the top left and go to APIs &amp; services-&gt;Credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSH046556RC7H7NN2Rc-UA.png" /></figure><p>Go to the bottom of the page, below Service accounts and click on the firebase-admin account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8E56u5Xuy6E-sWECjJvl_g.png" /></figure><p>When you log in, navigate to keys-&gt;add key and create a key in json format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3I-zAlMLoBVqrhQu2xOTWA.png" /></figure><p>The path of the downloaded key will be used in the -key-file parameter.</p><p>Once you have downloaded the json key, it is important that you open the file and look at the client_email field. This will contain the e-mail address where the key was created, in our case <a href="/service/mailto:firebase-adminsdk-w6z6d@integration-test-f.iam.gserviceaccount.com">firebase-adminsdk-w6z6d@integration-test-f.iam.gserviceaccount.com</a>.</p><p>This email must have editor access to the project, as it grants the permissions needed to carry out certain operations in gcloud.</p><p>To activate editor mode on this account, you need to go to the IAM tab, click on edit email and add the editor role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQkVceg7t-mmf6mFvJUdXg.png" /></figure><p>Once all these steps have been completed, the next step is to send our integration test to testlab.</p><p>to send the instrumentation test (android) to tastlab, use the command</p><pre>pushd build<br>           gcloud firebase test android run --type=instrumentation \<br>           --app &quot;app/outputs/apk/debug/app-debug.apk&quot; \<br>           --test &quot;app/outputs/apk/androidTest/debug/app-debug-androidTest.apk&quot; \<br>           --device-ids=MediumPhone.arm \<br>           --os-version-ids=33 \<br>           --orientations=portrait \<br>           --use-orchestrator \<br>           --timeout 3m</pre><p>Remember that this step requires the command to have been run first:</p><pre>pushd android<br># flutter build generates files in android/ for building the app<br>flutter build apk<br>./gradlew app:assembleAndroidTest<br>./gradlew app:assembleDebug -Ptarget=&lt;path_to_test&gt;.dart<br>popd</pre><p>To send XCTest(iOS) to testLab, use the command:</p><pre>output=&quot;build/ios_integ&quot;<br>product=&quot;ios/build/ios_integ/Build/Products&quot;<br>dev_target=&quot;15.7&quot;<br>flutter build ios integration_test/&lt;integratio_file_test&gt;.dart --release</pre><pre>pushd ios    xcodebuild build-for-testing \<br>    -workspace Runner.xcworkspace \<br>    -scheme Runner \<br>   # -xcconfig Flutter/Release.xcconfig \<br>    -configuration  Flutter/Release.xcconfig \<br>    -derivedDataPath \<br>    &quot;../build/ios_integ&quot; -sdk iphoneospopd<br>pushd $product<br>zip -r &quot;ios_tests.zip&quot; &quot;Release-iphoneos&quot; *.xctestrun <br>popd<br>gcloud firebase test ios run --test=&quot;ios/build/ios_integ/Build/Products/ios_tests.zip&quot; \<br>  --device model=iphone13pro,version=$dev_target,locale=en_US,orientation=portrait \</pre><h3>4 Pipeline</h3><p>The pipeline can be understood as a flow of processes with a beginning, middle and end. The purpose of these processes is to achieve a final goal. The pipeline allows us to see the complete flow of processes to achieve a goal. The idea of the pipeline is not only to contain the flow of processes until a certain task is accomplished, but also to automate processes, so that they don’t have to be done manually.</p><p>As an example of a pipeline, let’s imagine deploying a piece of code. The pipeline would have the process of installing the technology used to develop the code, installing environment variables, running unit tests, widget tests, integration tests and finally generating the executable for that code.</p><p>To create a pipeline we’ll use Github Actions.</p><h3>4.1 Github Actions</h3><p>Github actions is a CI/CD platform that allows us to automate processes via a pipeline. To use github actions, you must first have a registered github account and an active repository.</p><p>Go to your repository and click on the Actions option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRq44dMiIo1pDkk9LgrJNw.png" /></figure><p>Clicking on this option will bring up several pipelines with pre-set code for certain technologies.</p><p>In our case, we’re going to start making one from scratch. To create one from scratch, just click on the option <em>set up your workflow yourself</em> -&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EU_K3V0YnqV5b26jsu0ARQ.png" /></figure><p>The github actions will create a folder called .github/workflows and inside it will be a .yml file. This file will contain all our configuration. It will be our pipeline file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFXO1IFlGv1KPsnF-hM6Qg.png" /></figure><p>The marketplace contains features created by other users that can serve your purpose. They have pre-set commands that only require a few code snippets (there are some that don’t require any code snippets to work) from you for the command to be functional. As an example, I can mention a flutter installation feature, in which the command only requires the version of flutter we want to use to work.</p><p>Our goal now is to have our integration test triggered every time a change is uploaded to our github repository.</p><p>At this stage I’m going to take into account that you already know how to use Github and have some knowledge of Git.</p><p>I’ll post all the code and comment on the processes that I think are most important.</p><pre>name: integrationTest<br>on:<br>  push:<br>    branches: [&quot;main&quot;]jobs:<br>  integrationTest:<br>    name: integration Test<br>    runs-on: ubuntu-latest<br>    steps: <br>      - uses: actions/checkout@v3<br>      - uses: actions/setup-java@v3<br>        with:<br>          distribution: &#39;zulu&#39;<br>          java-version: &quot;17.x&quot;<br>          cache: gradle<br>          <br>      - uses: subosito/flutter-action@v2<br>        with:<br>          flutter-version: &quot;3.19.3&quot;<br>          channel: &#39;stable&#39;<br>          cache: true      - name: Flutter tests<br>        run: flutter test<br>        <br>      - name: Generate apk for testlab<br>        run: |<br>            pushd android<br>            flutter build apk<br>            ./gradlew app:assembleAndroidTest<br>            ./gradlew app:assembleDebug -Ptarget=&quot;integration_test/sign_in_test.dart&quot;<br>            popd      - uses: google-github-actions/setup-gcloud@v2.1.0<br>        with:<br>          project_id: &quot;integration-test-f&quot;<br>      - name: Download gcloud config json file<br>        id: gcloud_config<br>        uses: timheuer/base64-to-file@v1.0.3<br>        with:<br>            fileName: integration_test_gcloud.json<br>            encodedString: ${{  secrets.INTEGRATION_TEST_GCLOUD_CONFIG  }}      <br>        <br>      - name: Configure the gcloud account<br>        run: |<br>          <br>           gcloud auth activate-service-account --key-file=&quot;${{  steps.gcloud_config.outputs.filePath  }}&quot;<br>           pushd build<br>           gcloud firebase test android run --type=instrumentation \<br>           --app &quot;app/outputs/apk/debug/app-debug.apk&quot; \<br>           --test &quot;app/outputs/apk/androidTest/debug/app-debug-androidTest.apk&quot; \<br>           --device-ids=MediumPhone.arm \<br>           --os-version-ids=33 \<br>           --orientations=portrait \<br>           --use-orchestrator \<br>           --timeout 3m \</pre><p>Here I’ll explain the commands in general, and some specific points that need attention.</p><p>name: integrationTest is the name that will be shown as the tag for this pipeline in the actions on github.</p><p>on:<br>push:<br>branches: [“main”] -&gt; This command is used to specify that any push on the main branch will trigger our pipeline.</p><p>jobs: -&gt; this command is used to specify the jobs that the pipeline wants to hit.</p><p>runs-on: ubuntu-latest -&gt; the operating system of the virtual machine we want our code to run on.<br>steps: -&gt; define the steps for the job to be carried out<br>uses: -&gt; name of the repository<br>with: -&gt; sets the parameters<br>id: -&gt; creates a reference to the generated object.<br>run: | -&gt; works like a bash file, which can receive various instructions.</p><p>Github actions has a feature that allows you to save important information in variables called secrets. This usually saves important information that you don’t want to leave exposed in the pipeline.</p><p>In addition, secrets can be very helpful in long pipelines. Long pipelines can contain some information that changes periodically, such as the version of the tool we are using. Saving this version in secrets can save time looking for where this value is and modifying it. In this sense, they work like environment variables.</p><p>These variables can be called in our pipeline with the prefix<br>secrets.</p><p>The usage example is secret.&lt;secret_variable_name&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Smmcxu2aINMNISRh89XCOA.png" /></figure><p>Remember i mentioned that it’s important to use a command that links our firebase project to gcloud, which is a JSON file? Using secrets it is not possible to send files, so the strategy used to use the json file is</p><ol><li>Transform our gcloud settings json file into base64 code</li></ol><pre>openssl base64 -in &lt;file_name&gt;</pre><p>2. Save the generated code in a secret</p><p>3. Use a command that decodes base64</p><p>You can do this using the</p><pre>- name: Download gcloud config json file<br>        id: gcloud_config<br>        uses: timheuer/base64-to-file@v1.0.3<br>        with:<br>            fileName: integration_test_gcloud.json<br>            encodedString: ${{  secrets.INTEGRATION_TEST_GCLOUD_CONFIG  }}</pre><p>it is important to note that the gcloud_config id will be important for finding the path of this decoded file in the virtual machine. This id will be used in this passage of the pipeline</p><pre>- name: Configure the gcloud account<br>        run: |<br>           gcloud auth activate-service-account --key-file=&quot;${{  steps.gcloud_config.outputs.filePath  }}&quot;<br>           .<br>           .<br>           .</pre><p>The fileName: &lt;file_name&gt; must be the same as the one you saved on your machine, in my case the name of the json file is integration_test_gcloud.json.</p><h3>5. Conclusion</h3><p>This article is a compilation of the knowledge I have acquired over time, with many mistakes and improvements. If you try and fail at any stage (which I hope you won’t), don’t be discouraged, read the steps again or search a forum for the answers. Some of the information in this article may become deprecated over time. Building a pipeline is time-consuming, mistakes happen more often than expected and you have to run the pipeline, see the feedback from the mistake, make the improvement and run the pipeline again. It’s not an easy process, but once it’s implemented and working, it saves us precious time.</p><p>Access my Github repository containing the implementation of a flutter project with tests and pipeline by clicking <a href="https://github.com/MatheusHenriq/integration_test">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*cZIB1wnIRE2JoLR2qtkONQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31ba1f2c173c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testes de integração no flutter com gcloud, firebase e Github Actions]]></title>
            <link>https://medium.com/@matheusdeveloper.henrique/testes-de-integra%C3%A7%C3%A3o-no-flutter-com-gcloud-e-firebase-e-github-actions-0b9546cf2cca?source=rss-f7b76e54cd9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b9546cf2cca</guid>
            <category><![CDATA[g-cloud]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Matheus Henrique de Souza Fontenele]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 14:18:55 GMT</pubDate>
            <atom:updated>2024-04-07T19:48:13.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*VJrg1SN1tCxccsIPXwksjA.jpeg" /></figure><p>Olá, pessoal, no final desse artigo vocês estarão aptos a criar uma pipeline que tem por objetivo enviar testes de integração android/iOS para o Firebase TestLab. Então vamos lá.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*M3-SHBMWOhLJ1aLgMSBCkg.gif" /></figure><p>Para ficar mais organizado, vamos falar sobre esses tópicos em sequência.</p><ol><li>Testes de integração</li><li>Firebase</li><li>Gcloud</li><li>Pipeline(Github Actions)</li><li>Conclusão</li></ol><h3>1. Testes de integração</h3><p>Testes de integração são uma etapa do desenvolvimento de software onde os componentes são testados em conjunto. Ela geralmente é realizada após os testes unitários e de widgets(no contexto do Flutter).</p><p>Ela é a última etapa pois a ideia é testar o funcionamento combinando de todos os componentes pra realizar uma determinada função.</p><p>Como exemplo podemos imaginar um fluxo de autenticação, no qual os testes teriam as seguintes responsabilidades:</p><p>Unitários(funções):</p><ul><li>Testar retornos da API</li><li>Testar fluxos Corretos na autenticação</li><li>Testar casos de falhas na autenticação</li></ul><p>Widgets(Componentes):</p><ul><li>Testar o funcionamento dos botões</li><li>Testar responsividade baseado em mudanças de estados da página.</li></ul><p>Integração:</p><ul><li>Testar o funcionamento de funcionalidades combinadas.</li><li>Verificar se o aplicativo está conseguindo realizar um fluxo sem erros.</li></ul><p>Os testes de integração são guiados por chaves em componentes. Essa chave vai fazer um link com aquele componente específico e com isso podemos:</p><ul><li>Verificar em qual componente estamos</li><li>Se a página atual possui aquele componente</li><li>Realizar alguma ação, tais como:</li><li>Clicar em um botão.</li><li>Navegar para outra tela.</li><li>Escrever em um campo de texto.</li></ul><p>Para realizar os testes de integração é necessário criar uma pasta no diretório raiz do projeto flutter chamado integration_test e dentro dessa pasta criar o nosso arquivo de teste.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvDFsbFZTOcYKJtOlEDhcA.png" /></figure><h3>2. Firebase</h3><p>O firebase é um conjunto de serviços em nuvem fornecido pela Google. O firebase e flutter tem uma compatibilidade muito fluida por serem ambas tecnologias desenvolvidas pela equipe do Google.</p><p>Dentre os vários serviços fornecidos pelo Firebase, o que vamos abordar no artigo será o TestLab.</p><p>O Testlab por sua vez só pode ser utilizado quando se existe um projeto ativo no firebase.</p><h3>2.1: Criando um projeto no firebase</h3><p>Para criar um projeto no firebase acesse a página do firebase <a href="https://firebase.google.com/?hl=pt-br">aqui</a> , e clique em Go to console.</p><p>Dentro dessa página, clique em adicionar projeto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VfihMZLO_cFi40yQmr4wA.png" /></figure><p>Após isso você pode criar seu aplicativo android e ios, com os respectivos applicationId e bundleId. Fazer isso de forma manual pode ser incomodo.<br>O flutter tem uma integração ótima com o firebase, o que nos permite, por exemplo, criar aplicativos em um projeto no firebase via linhas de comando utilizando o flutterfire.</p><p>FlutterFire é um conjunto de plugins que conectam flutter e firebase.</p><p>Para instalar o firebase na sua máquina, utilize o comando</p><pre>npm install firebase-tools -g</pre><p>Após isso, navegue até seu projeto flutter e rode os comandos</p><pre>export PATH=&quot;$PATH&quot;:&quot;$(DartToolPath)&quot;<br>dart pub global activate flutterfire_cli</pre><p>Uma vez que o flutterfire_cli esteja instalado, utilize o comando para criar os aplicativos diretos na conta do projeto que você criou.</p><pre>export PATH=&quot;$PATH&quot;:&quot;$(DartToolPath)&quot;<br>export PATH=&quot;$PATH&quot;:&quot;$HOME/.pub-cache/bin&quot;</pre><pre>flutterfire configure \<br>--project=&lt;firebase_project_id&gt; \ #Id do projeto criado(Ao acessar a página do firebase, irá aparecer o nome do seu projeto e abaixo a id associado a ele.<br>--platforms=android,ios \ #plataformas que serão criados os aplicativos.<br>--android-package-name=&lt;applicationId&gt; \ -&gt; aplicationID do android<br>--ios-bundle-id=&lt;BundleId&gt; \ --bundleId do iOS<br>-y --token=&lt;FIREBASE_TOKEN&gt;</pre><p>Para capturar o firebase token, utilize o comando</p><pre>firebase login:ci</pre><p>ele irá redirecionar pra suas contas da google. Acessando a conta que você utilizou para criar o projeto no firebase e aceitando os termos, você receberá o token no terminal no qual enviou o comando firebase login:ci.</p><p>Importante lembrar que esse token gerado é referente a sua conta, ou seja, ele funciona para todos os projetos já criados e que ainda irão ser criados, então mantenha ele seguro.</p><p>OBS: Pode ser complicado executar todos esses comandos um por vez, caso queira executar todos de uma só vez, uma abordagem interessante é criar um arquivo .sh, dar permissão para execução e colocar esses comandos dentro do arquivo.</p><p>Um exemplo disso seria colocar esses último comando contendo o export até o -y — token dentro de um arquivo chamado, por exemplo, create_firebase_projs.sh e dar o comando chmod +x create_firebase_projs.sh. Esse comando dá a permissão de execução do arquivo.</p><p>Para rodar esse comando, acesse o diretório onde ele se encontra e digite no terminal ./create_firebase_projs.sh</p><h3>2.2 TestLab</h3><p>O TestLab é uma infraestrutura de testes de aplicativos que se baseia na nuvem pra disponibilizar x números de devices e configurações para testes de integração. Ele utiliza o data center da Google pra gerar um device e testar o aplicativo.</p><p>Ele disponibiliza 4 tipos de testes:</p><ul><li>Testes de instrumentação — Android</li><li>Teste Robo — Android</li><li>Teste de loop para jogos — Android/iOS</li><li>XCTest — iOS.</li></ul><p>Iremos utilizar 2 tipos de testes. Para android, utilizaremos o teste de instrumentação e para o iOS o XCTest.</p><p>O Firebase testlab utiliza 3 conceitos:</p><p>Dispositivo</p><ul><li>Essa etapa é referente a escolha do dispositivo(device) a ser utilizado no teste. Esse teste leva em consideração se é dispositivo é um smartphone, tablet ou um dispositivo wearable. Esses dispositivos são identificados por modelo, versão do S.O, orientação da tela(portrait, landscape) e localidade.</li></ul><p>Teste, execução to teste</p><ul><li>É basicamente o conjunto de testes realizados em um dispositivo selecionado. Existe a possibilidade de testar por dispositivo ou fragmentar o teste e executar em diferentes dispositivos(dependendo de quantos dispositivos se escolha pra realizar o teste).</li></ul><p>Matriz de teste</p><ul><li>Aqui será mostrado os resultados dos testes realizados nos dispositivos selecionados. É importante lembrar que se for escolhido N dispositivos de teste e em algum deles o teste falhar a matriz inteira receberá uma flag de falha e será interrompida.</li></ul><p>Em suma, é só seguir a seguinte regra <strong>Dispositivos × Execuções de teste = Matriz de teste</strong></p><h3>2.3 Teste de instrumentação — Configuração Android</h3><p>Para utilizar o teste de instrumentação do android, é necessário adicionar certas configurações no projeto android.</p><p>A primeira delas é acessar a pasta android/app/src e criar o arquivo androidTest.</p><p>Vamos levar em consideração que nosso projeto tem o seguinte applicationId -&gt; com.example.integrationtest</p><p>Ao criar a pasta androidTest criamos também as pastas java/com/example/integrationtest</p><p>Dentre dessa última pasta, criamos um arquivo chamando MainActivityTest.java(pode ser o nome do seu agrado).</p><p>Logo, o caminho total será -&gt;android/app/src/androidTest/java/com/example/integrationtest/MainActivityTest.java</p><p>Nesse arquivo java, coloque o seguinte trecho de código:</p><pre>package com.example.integrationtest;</pre><pre>import androidx.test.rule.ActivityTestRule;<br>import dev.flutter.plugins.integration_test.FlutterTestRunner;<br>import org.junit.Rule;<br>import org.junit.runner.RunWith;</pre><pre>@RunWith(FlutterTestRunner.class)<br>public class MainActivityTest {<br>  @Rule<br>  public ActivityTestRule&lt;MainActivity&gt; rule = new ActivityTestRule&lt;&gt;(MainActivity.class, true, false);<br>}</pre><p>Após isso, na pasta android/app/build.gradle, adicione os comandos:</p><pre>android {<br>  ...<br>  defaultConfig {<br>    ...<br>    testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>  }<br>}</pre><pre>dependencies {<br>    testImplementation &#39;junit:junit:4.12&#39;</pre><pre>    // <a href="https://developer.android.com/jetpack/androidx/releases/test/#1.2.0">https://developer.android.com/jetpack/androidx/releases/test/#1.2.0</a><br>    androidTestImplementation &#39;androidx.test:runner:1.2.0&#39;<br>    androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.2.0&#39;<br>}</pre><p>Após finalizar essas etapas, você está apto a gerar um teste de instrumentação para android.</p><p>Para gerar um teste de instrumentação, utilize os comandos</p><pre>pushd android<br># flutter build generates files in android/ for building the app<br>flutter build apk<br>./gradlew app:assembleAndroidTest<br>./gradlew app:assembleDebug -Ptarget=&lt;path_to_test&gt;.dart<br>popd</pre><p>Ou se preferir, crie um arquivo com essas informações e execute-o.</p><p>Aqui vai um exemplo:<br>Crie um arquivo chamado de android_integrationTest.sh(nome fica a seu critério)<br>Após isso, utilize o comando chmod +x android_integrationTest.sh</p><p>O comando chmod +x da permissão do arquivo especificado de execução e autorização.</p><p>Dentro de android_integrationTest.sh coloque os últimos comandos escritos acima.</p><p>Para executar tudo automaticamente, apenas escreva ./android_integrationTest.sh no diretório onde o arquivo foi criado.</p><p>Ao enviar esses comandos, irá ser criado na pasta build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk o apk de testes e na pasta build/app/outputs/apk/release/app-release.apk o apk release.</p><p>Esses dois apks podem ser utilizados para fazer o teste de forma manual clicando <a href="https://console.firebase.google.com/u/2/project/integration-test-f/testlab/run/instrumentation">aqui</a>.</p><h3>2.4 Criando XCTEST no iOS</h3><p>Para utilizar o XCTEST no iOS, é necessário adicionar certas configurações no projeto iOS.</p><p>A primeira delas é criar um arquivo RunnerTests dentro da pasta iOS. Porém isso deve ser feito via XCode &gt; File &gt; New &gt; Target. Após isso filtre pela opção Unit Testing Bundle, e Crie um target chamado RunnerTests com a linguagem Obj-C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cug7kDfI8ehkYNAtTIDPJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVpEBOwwxTrodWk9KKEAWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2uHtVWARbaT4py1VNzfVQ.png" /></figure><p>Uma vez criado o target, uma pasta chamada RunnerTests irá aparecer dentro da pasta ios(ios/RunnerTests/RunnerTests.m).</p><p>Apague o conteúdo que tem dentro da RunnerTests.m e insira o código:</p><pre>@import XCTest;<br>@import integration_test;<br>INTEGRATION_TEST_IOS_RUNNER(RunnerTests)</pre><p>O próximo passo é acessar o Podfile dentro da pasta ios e adicionar os comandos:</p><pre>Target &#39;Runner&#39; do<br>  # Do not change existing lines.<br>  ...<br><br>  target &#39;RunnerTests&#39; do <br>    inherit! :search_paths<br>  end<br>end</pre><p>Uma vez finalizado, o setup para o XCTEST está pronto para ser utilizado.</p><p>O processo a se seguir é parecido com o que utilizamos no teste de instrumentação do Android.</p><p>O arquivo criado para teste tem de conter os seguintes comandos</p><pre>output=&quot;../build/ios_integ&quot;<br>product=&quot;build/ios_integ/Build/Products&quot;</pre><pre># Pass --simulator if building for the simulator.<br>flutter build ios integration_test/&lt;integration_test_file&gt; --release</pre><pre>pushd ios<br>xcodebuild build-for-testing \<br>  -workspace Runner.xcworkspace \<br>  -scheme Runner \<br>  -xcconfig Flutter/Release.xcconfig \<br>  -configuration Release \<br>  -derivedDataPath \<br>  $output -sdk iphoneos<br>popd</pre><pre>pushd $product<br>find . -name &quot;Runner_*.xctestrun&quot; -exec zip -r --must-match &quot;ios_tests.zip&quot; &quot;Release-iphoneos&quot; {} +<br>popd</pre><p>Após isso será criado um arquivo zip na pasta ios/build/ios_integ/Build/Products<br>com nome de ios_test.zip</p><p>Esse arquivo pode ser utilizado para pra realizar o teste clicando <a href="https://console.firebase.google.com/u/2/project/integration-test-f/testlab/run/xctest">aqui</a></p><h3>3. Gcloud</h3><p>Subir manualmente arquivos para serem testados é uma solução interessante quando não se tem a possibilidade de subir tudo de uma vez via comandos. Esse não é o caso, com o Gcloud isso é possível.</p><p>Gcloud é, em suma, um conjunto recursos físicos e virtuais localizados nos data centers da Google localizados por todo o globo terrestre. Ele possui uma gama de serviços que podem ser acessadas clicando <a href="https://cloud.google.com/products?hl=pt-br">aqui</a>.</p><p>Vamos utilizar o Gcloud CLI, que é um conjunto de ferramentas com o intuito de criar e gerenciar recursos do Google Cloud. Esses serviços são utilizados pra executar scripts de automação, entre outras coisas.</p><h3>3.1 — Utilização da Gcloud CLI</h3><p>O primeiro passo para utilizar o gCloud é a instalação na sua máquina. A instalação pode ser realizada clicando <a href="https://cloud.google.com/sdk/docs/install?hl=pt-br">aqui</a>.</p><p>Uma vez que o Gcloud foi instalado, o próximo passo é aplicar nas configurações do gcloud o id do seu projeto e um arquivo de especificação.</p><p>Para especificar o projeto, utilize o comando</p><pre>gcloud config set project &lt;firebase_project_id&gt;</pre><p>Outro ponto principal é quando queremos fazer o vínculo do Gcloud com o nosso projeto no firebase para permitir o uso total da ferramenta. Para isso é necessário um arquivo de configuração do projeto do firebase e setar o arquivo no gcloud.</p><p>O comando para fazer isso é:</p><pre>gcloud auth activate-service-account --key-file=&quot;../&lt;gcloud_config_for_firebase_project.json&gt;&quot;</pre><p>Para conseguir esse arquivo é necessário cria-lo e baixa-lo.</p><p>Para criar, navegue pela página do gcloud console <a href="https://console.cloud.google.com/welcome?hl=pt-br">aqui</a>.</p><p>É importante que o perfil de acesso seja o mesmo que você utilizou pra criar o projeto no firebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWk6jCUK_hd8glUnHIze8A.png" /></figure><p>Ao lado de Google Cloud, no canto superior esquerdo, estarão seus projetos no firebase, selecione o projeto que você quer utilizar.</p><p>Após isso clique em IAM e administrador, clique no menu no canto superior esquerdo e vá até APIs e serviços-&gt;Credenciais.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEKgRZwqcKn5WK60rLTKZA.png" /></figure><p>Navegue até o final da página, em Contas de serviço e clique na conta firebase-admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mLzQ7jKRSZRS18ER0bDLg.png" /></figure><p>Ao entrar navegue por chaves-&gt;adicionar chave e crie um chave no formato json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKqD9xsqGflG9E9HnvjWzQ.png" /></figure><p>O caminho da chave baixada será utilizado no pârametro — key-file.</p><p>Uma vez baixada a chave json, é importante que você abra o arquivo e olhe o campo client_email. Nele terá o e-mail onde foi criado a chave, no nosso caso foi o e-mail <a href="/service/mailto:firebase-adminsdk-w6z6d@integration-test-f.iam.gserviceaccount.com">firebase-adminsdk-w6z6d@integration-test-f.iam.gserviceaccount.com</a>.</p><p>Esse e-mail deve ter acesso editor no projeto, pois ele garante permissões necessárias para realizar algumas operações no gcloud.</p><p>Para ativar o modo editor nessa conta, é necessário acessar a aba IAM, clicar em editar o e-mail e adicionar o papel de editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObbNgdYk2IADoD9Q1Vxgiw.png" /></figure><p>Uma vez realizada todas essas etapas, o próximo passo e enviar o nosso teste de integração para o testlab.</p><p>para enviar o teste de instrumentação(android) para o tastlab, utilize o comando</p><pre>pushd build<br>           gcloud firebase test android run --type=instrumentation \<br>           --app &quot;app/outputs/apk/debug/app-debug.apk&quot; \<br>           --test &quot;app/outputs/apk/androidTest/debug/app-debug-androidTest.apk&quot; \<br>           --device-ids=MediumPhone.arm \<br>           --os-version-ids=33 \<br>           --orientations=portrait \<br>           --use-orchestrator \<br>           --timeout 3m</pre><p>Lembrando que essa etapa requer que esse comando tenha rodado antes:</p><pre>pushd android<br># flutter build generates files in android/ for building the app<br>flutter build apk<br>./gradlew app:assembleAndroidTest<br>./gradlew app:assembleDebug -Ptarget=&lt;path_to_test&gt;.dart<br>popd</pre><p>Para enviar o XCTest(iOS) para o testLab, utilize o comando:</p><pre>output=&quot;build/ios_integ&quot;<br>product=&quot;ios/build/ios_integ/Build/Products&quot;<br>dev_target=&quot;15.7&quot;<br>flutter build ios integration_test/&lt;integratio_file_test&gt;.dart --release</pre><pre>pushd ios</pre><pre>    xcodebuild build-for-testing \<br>    -workspace Runner.xcworkspace \<br>    -scheme Runner \<br>   # -xcconfig Flutter/Release.xcconfig \<br>    -configuration  Flutter/Release.xcconfig \<br>    -derivedDataPath \<br>    &quot;../build/ios_integ&quot; -sdk iphoneos</pre><pre>popd<br>pushd $product<br>zip -r &quot;ios_tests.zip&quot; &quot;Release-iphoneos&quot; *.xctestrun <br>popd<br></pre><pre>gcloud firebase test ios run --test=&quot;ios/build/ios_integ/Build/Products/ios_tests.zip&quot; \<br>  --device model=iphone13pro,version=$dev_target,locale=en_US,orientation=portrait \</pre><h3>4 Pipeline</h3><p>A pipeline pode ser entendida como um fluxo de processos com começo, meio e fim. A realização desses processos tem por intuito um objetivo final. A pipeline nos permite ver o fluxo completo de processos para atingir um objetivo. A ideia da pipeline é, além de conter o fluxo dos processos até ser realizado determinada tarefa, a automação de processos, não necessitando que ele seja feito manualmente.</p><p>Como exemplo de uma pipeline vamos imaginar o deploy de um código. A pipeline teria o processo de instalação da tecnologia utilizada para desenvolver o código, a instalação de variáveis de ambiente, rodar testes unitários, de widget, integração, e por fim gerar o executável daquele código.</p><p>Para criarmos uma pipeline vamos utilizar o Github Actions.</p><h3>4.1 Github Actions</h3><p>O Github actions é uma plataforma de CI/CD que nos permite automatizar processos via pipeline. Para utilizar o github actions é necessário antes ter uma conta cadastrada no github e um repositório ativo.</p><p>Acesse o seu repositório e clique na opção Actions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRq44dMiIo1pDkk9LgrJNw.png" /></figure><p>Ao clicar nessa opção irá aparecer várias pipelines com códigos pré setados pra determinadas tecnologias.</p><p>No nosso caso, vamos começar a fazer uma do zero. Para criar uma do zero é só clicar na opção <em>set up your workflow yourself</em> -&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EU_K3V0YnqV5b26jsu0ARQ.png" /></figure><p>O github actions irá criar uma pasta chamada .github/workflows e dentro dela irá conter um arquivo .yml. Esse arquivo irá receber toda a nossa configuração. Ele será o nosso arquivo de pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFXO1IFlGv1KPsnF-hM6Qg.png" /></figure><p>O marketplace contém funcionalidade criadas por outros usuários que podem atender ao seu objetivo. Eles tem comandos pré setados que esperam apenas alguns trechos de código(tem alguns que não esperam trecho de código algum para funcionar) seu para que o comando fique funcional, como exemplo posso citar uma funcionalidade de instalação do flutter, no qual o comando requer pra funcionar apenas a versão do flutter que queremos que seja utilizado.</p><p>O nosso objetivo agora é fazer com que nosso teste de integração seja acionado toda vez que uma mudança subir pra o nosso repositório no github.</p><p>Nessa etapa vou levar em consideração que você já saiba utilizar o Github e tenha conhecimentos de Git.</p><p>Vou colocar todo o código e tecer comentários sobre os processos que acho mais importantes.</p><pre>name: integrationTest</pre><pre>on:<br>  push:<br>    branches: [&quot;main&quot;]</pre><pre>jobs:<br>  integrationTest:<br>    name: integration Test<br>    runs-on: ubuntu-latest<br>    steps: <br>      - uses: actions/checkout@v3<br>      - uses: actions/setup-java@v3<br>        with:<br>          distribution: &#39;zulu&#39;<br>          java-version: &quot;17.x&quot;<br>          cache: gradle<br>          <br>      - uses: subosito/flutter-action@v2<br>        with:<br>          flutter-version: &quot;3.19.3&quot;<br>          channel: &#39;stable&#39;<br>          cache: true</pre><pre>      - name: Flutter tests<br>        run: flutter test<br>        <br>      - name: Generate apk for testlab<br>        run: |<br>            pushd android<br>            flutter build apk<br>            ./gradlew app:assembleAndroidTest<br>            ./gradlew app:assembleDebug -Ptarget=&quot;integration_test/sign_in_test.dart&quot;<br>            popd</pre><pre>      - uses: google-github-actions/setup-gcloud@v2.1.0<br>        with:<br>          project_id: &quot;integration-test-f&quot;<br>      - name: Download gcloud config json file<br>        id: gcloud_config<br>        uses: timheuer/base64-to-file@v1.0.3<br>        with:<br>            fileName: integration_test_gcloud.json<br>            encodedString: ${{  secrets.INTEGRATION_TEST_GCLOUD_CONFIG  }}      <br>        <br>      - name: Configure the gcloud account<br>        run: |<br>          <br>           gcloud auth activate-service-account --key-file=&quot;${{  steps.gcloud_config.outputs.filePath  }}&quot;<br>           pushd build<br>           gcloud firebase test android run --type=instrumentation \<br>           --app &quot;app/outputs/apk/debug/app-debug.apk&quot; \<br>           --test &quot;app/outputs/apk/androidTest/debug/app-debug-androidTest.apk&quot; \<br>           --device-ids=MediumPhone.arm \<br>           --os-version-ids=33 \<br>           --orientations=portrait \<br>           --use-orchestrator \<br>           --timeout 3m \</pre><p>Aqui vou abordar a explicação dos comandos de forma geral, e alguns pontos específicos que precisam de atenção.</p><p>name: integrationTest é o nome que irá ser mostrado como tag dessa pipeline no actions no github</p><p>on:<br>push:<br>branches: [“main”] -&gt; Esse comando é utilizado para, em linhas gerais, especificar que qualquer push na branch main irá acionar nossa pipeline.</p><p>jobs: -&gt; esse comando é utilizado para especificar os trabalhos que a pipeline quer atingir.</p><p>runs-on: ubuntu-latest -&gt; o sistema operacional da máquina virtual que queremos que nosso código rode.<br>steps: -&gt; define os passos para que o job seja realizado<br>uses: -&gt; nome do repositorio<br>with: -&gt; seta os parâmetros<br>id: -&gt; cria-se uma referência ao objeto gerado.<br>run: | -&gt; funciona como um arquivo bash, que pode receber várias instruções.</p><p>O Github actions tem uma funcionalidade que permite que salvemos alguma informação importante em variáveis chamadas de secrets. Geralmente se salva informações importantes que não é interessante deixar exposta na pipeline.</p><p>Além disso, secrets podem ser de grande ajuda em pipelines extensas. As pipelines extensas podem conter algumas informações que mudam periodicamente, como exemplo podemos citar a versão da ferramenta que estamos utilizando. Salvar essa versão nas secrets pode poupar tempo procurando o local onde esse valor está e modica-lo. Nesse sentido, elas funcionariam como variáveis de ambiente.</p><p>Essas variáveis podem sem chamadas na nossa pipeline com o prefixo<br>secrets.</p><p>O exemplo de uso é secret.&lt;secret_variable_name&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Smmcxu2aINMNISRh89XCOA.png" /></figure><p>Lembram que citei que é importante utilizar um comando que faz o vínculo com nosso projeto no firebase com o gcloud que se dá por um arquivo JSON? Utilizando secrets não se é possível enviar arquivos, logo a estratégia utilizada para utilizar o arquivo json é</p><ol><li>Transformar nosso arquivo json de configurações do gcloud em um código em base64</li></ol><pre>openssl base64 -in &lt;file_name&gt;</pre><p>2. Salvar o código gerado em uma secret</p><p>3. Utilizar um comando que decodifique uma base64</p><p>Isso é possível através do comando</p><pre>- name: Download gcloud config json file<br>        id: gcloud_config<br>        uses: timheuer/base64-to-file@v1.0.3<br>        with:<br>            fileName: integration_test_gcloud.json<br>            encodedString: ${{  secrets.INTEGRATION_TEST_GCLOUD_CONFIG  }}</pre><p>é importante ressaltar que o id gcloud_config irá ser importante pra conseguirmos achar o caminho desse arquivo decodificado na máquina virtual. Esse id será utilizado nessa passagem da pipeline</p><pre>- name: Configure the gcloud account<br>        run: |<br>           gcloud auth activate-service-account --key-file=&quot;${{  steps.gcloud_config.outputs.filePath  }}&quot;<br>           .<br>           .<br>           .</pre><p>O fileName: &lt;file_name&gt; tem de ser igual ao que você salvou na sua máquina, no meu caso o nome do arquivo json é integration_test_gcloud.json.</p><h3>5. Conclusão</h3><p>Esse artigo é um compilado dos conhecimentos que consegui adquirir ao longo do tempo, com muitos erros e melhoras. Caso tente fazer e não consiga em alguma etapa(o que eu espero que não aconteça), não desanime, leia os passos novamente ou pesquise em algum fórum as respostas. Algumas informações nesse artigo com o passar do tempo podem ficar depreciadas. A construção de uma pipeline é algo demorado, os erros acontecem com mais frequência que o esperado e é preciso rodar a pipeline, ver o feedback do erro, fazer a melhora e rodar a pipeline novamente. Não é um processo fácil, mas uma vez implementado e funcional nos poupa um tempo precioso.</p><p>Acesse meu repositório no Github contendo a implementação de um projeto em flutter com testes e pipeline clicando <a href="https://github.com/MatheusHenriq/integration_test">aqui</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*cZIB1wnIRE2JoLR2qtkONQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b9546cf2cca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>