<?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 Serkan on Medium]]></title>
        <description><![CDATA[Stories by Serkan on Medium]]></description>
        <link>https://medium.com/@srkan?source=rss-3bf919b049c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QyDG2JGr5f3He5iL</url>
            <title>Stories by Serkan on Medium</title>
            <link>https://medium.com/@srkan?source=rss-3bf919b049c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:54:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srkan/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[QR Code Scanner & Generator App with Flutter]]></title>
            <link>https://medium.com/@srkan/qr-code-scanner-generator-app-with-flutter-95a5722d0be2?source=rss-3bf919b049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/95a5722d0be2</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[qr-code]]></category>
            <dc:creator><![CDATA[Serkan]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 12:58:44 GMT</pubDate>
            <atom:updated>2025-04-30T12:58:44.524Z</atom:updated>
            <content:encoded><![CDATA[<p>I built a simple app that allows users to <strong>scan</strong> and <strong>generate QR codes</strong> with ease.</p><p>Source Code: <a href="https://github.com/serkan-y38/Flutter-QR">https://github.com/serkan-y38/Flutter-QR</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlnjQfoDU1pby9yt8NRU4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VExEoA44IAFByz4l0NPhpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXq29EmToYqrem-2mR_MtQ.png" /></figure><h4><strong>Packages Used</strong></h4><ul><li>mobile_scanner – for QR code scanning.</li><li>pretty_qr_code – to generate QR codes.</li><li>path_provider – for accessing temporary directories for saving files.</li><li>gal – to save generated QR images directly to the device gallery.</li><li>share_plus – to share QR code images.</li></ul><h4>Let’s Code</h4><p>Add the following packages under the dependencies: section in your pubspec.yaml file:</p><pre>... <br><br>dependencies:<br>  flutter:<br>    sdk: flutter<br><br>  ...<br><br>  mobile_scanner: ^6.0.10<br>  pretty_qr_code: ^3.4.0<br>  path_provider: ^2.1.5<br>  gal: ^2.3.1<br>  share_plus: ^11.0.0<br><br>...</pre><p>To simplify navigation, I defined all route names in NavRoute and used NavRouter with onGenerateRoute to manage screen transitions and handle unknown routes consistently.</p><pre>class NavRoute {<br>  static const String homeScreen = &quot;homeScreen&quot;;<br>  static const String qrCodeScannerScreen = &quot;qrCodeScannerScreen&quot;;<br>}</pre><pre>class NavRouter {<br>  static Route&lt;dynamic&gt; generateRoute(RouteSettings settings) {<br>    switch (settings.name) {<br>      case NavRoute.qrCodeScannerScreen:<br>        return MaterialPageRoute(builder: (_) =&gt; const QRCodeScannerScreen());<br>      case NavRoute.homeScreen:<br>        return MaterialPageRoute(builder: (_) =&gt; const HomeScreen());<br>      default:<br>        return MaterialPageRoute(<br>          builder: (_) =&gt; Scaffold(<br>            body: Center(child: Text(&#39;No route defined for ${settings.name}&#39;)),<br>          ),<br>        );<br>    }<br>  }<br>}</pre><p>In main.dart, I set up the app&#39;s navigation using onGenerateRoute with NavRouter and defined the initial route as homeScreen. I also applied a dynamic theme that switches between light and dark mode based on the system&#39;s brightness using MediaQuery.</p><pre>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter QR&#39;,<br>      debugShowCheckedModeBanner: false,<br>      onGenerateRoute: NavRouter.generateRoute,<br>      initialRoute: NavRoute.homeScreen,<br>      theme: (MediaQuery.of(context).platformBrightness == Brightness.dark)<br>          ? darkTheme<br>          : lightTheme,<br>    );<br>  }<br>}</pre><p>I built a HomeScreen that includes a TextField for entering custom text, along with two main actions: one to generate a QR code and another to navigate to the QR code scanner screen.</p><pre>class HomeScreen extends StatefulWidget {<br>  const HomeScreen({super.key});<br><br>  @override<br>  State&lt;HomeScreen&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;HomeScreen&gt; {<br>  late TextEditingController _textEditingController;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _textEditingController = TextEditingController();<br>  }<br><br>  @override<br>  void dispose() {<br>    super.dispose();<br>    _textEditingController.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: SingleChildScrollView(<br>        child: Padding(<br>          padding: const EdgeInsets.only(<br>            left: 16,<br>            right: 16,<br>            bottom: 16,<br>            top: 8,<br>          ),<br>          child: Column(<br>            children: [<br>              SizedBox(<br>                height: 32,<br>              ),<br>              Icon(<br>                Icons.qr_code_2_rounded,<br>                size: 224,<br>              ),<br>              SizedBox(<br>                height: 16,<br>              ),<br>              TextField(<br>                maxLines: null,<br>                controller: _textEditingController,<br>                textInputAction: TextInputAction.newline,<br>                decoration: InputDecoration(<br>                  filled: true,<br>                  fillColor: Theme.of(context).colorScheme.surfaceContainerHigh,<br>                  hintText: &quot;Enter text&quot;,<br>                  labelText: &quot;Enter Text To Generate QR Code&quot;,<br>                  prefixIcon: const Icon(Icons.data_object),<br>                  border: const UnderlineInputBorder(),<br>                ),<br>              ),<br>              SizedBox(<br>                height: 16,<br>              ),<br>              TextButton(<br>                onPressed: () {<br>                  (_textEditingController.text != &quot;&quot;)<br>                      ? _showQRCode()<br>                      : WidgetsBinding.instance.addPostFrameCallback((_) {<br>                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(<br>                              content: Text(&quot;Enter Text To Generate QR Code&quot;)));<br>                        });<br>                },<br>                style: TextButton.styleFrom(<br>                  backgroundColor:<br>                      Theme.of(context).colorScheme.primaryContainer,<br>                  minimumSize: const Size(double.infinity, 48),<br>                ),<br>                child: Text(<br>                  &quot;Generate QR Code&quot;,<br>                  style: Theme.of(context).textTheme.labelLarge?.copyWith(<br>                      color: Theme.of(context).colorScheme.onPrimaryContainer),<br>                ),<br>              ),<br>              SizedBox(<br>                height: 16,<br>              ),<br>              TextButton(<br>                onPressed: () {<br>                  Navigator.pushNamed(context, NavRoute.qrCodeScannerScreen);<br>                },<br>                style: TextButton.styleFrom(<br>                  minimumSize: const Size(double.infinity, 48),<br>                  backgroundColor:<br>                      Theme.of(context).colorScheme.surfaceContainerHighest,<br>                ),<br>                child: Text(<br>                  &quot;Scan QR Code&quot;,<br>                  style: Theme.of(context).textTheme.labelLarge?.copyWith(<br>                      color: Theme.of(context).colorScheme.onPrimaryContainer),<br>                ),<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  Future&lt;void&gt; _showQRCode() {<br>    return showModalBottomSheet(<br>      showDragHandle: true,<br>      isScrollControlled: true,<br>      useSafeArea: true,<br>      enableDrag: true,<br>      context: context,<br>      builder: (BuildContext context) {<br>        return GenerateQRBottomSheet(<br>          text: _textEditingController.text,<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>I created a GenerateQRBottomSheet that displays a QR code generated from input text. Users can save it to the gallery or share it via the share_plus package. The QR is captured with RepaintBoundary and converted to an image for both actions.</p><pre>class GenerateQRBottomSheet extends StatefulWidget {<br>  final String text;<br><br>  const GenerateQRBottomSheet({<br>    super.key,<br>    required this.text,<br>  });<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() {<br>    return _Content();<br>  }<br>}<br><br>class _Content extends State&lt;GenerateQRBottomSheet&gt; {<br>  late QrCode _qrCode;<br>  late QrImage _qrImage;<br><br>  final GlobalKey _globalKey = GlobalKey();<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _qrCode = QrCode.fromData(<br>      data: widget.text,<br>      errorCorrectLevel: QrErrorCorrectLevel.H,<br>    );<br><br>    _qrImage = QrImage(_qrCode);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Column(<br>        children: [<br>          Padding(<br>            padding: EdgeInsets.all(16),<br>            child: SizedBox(<br>              height: MediaQuery.of(context).size.width,<br>              width: MediaQuery.of(context).size.width,<br>              child: RepaintBoundary(<br>                key: _globalKey,<br>                child: PrettyQrView(<br>                  qrImage: _qrImage,<br>                  decoration: PrettyQrDecoration(<br>                    background: Colors.transparent,<br>                    quietZone: PrettyQrQuietZone.zero,<br>                    shape: PrettyQrSmoothSymbol(<br>                      color: Theme.of(context).colorScheme.onSurface,<br>                      roundFactor: 1,<br>                    ),<br>                  ),<br>                ),<br>              ),<br>            ),<br>          ),<br>          Padding(<br>            padding: EdgeInsets.only(<br>              left: 16,<br>              right: 16,<br>              bottom: 16,<br>            ),<br>            child: TextButton(<br>              onPressed: () {<br>                save();<br>              },<br>              style: TextButton.styleFrom(<br>                backgroundColor: Theme.of(context).colorScheme.primaryContainer,<br>                minimumSize: const Size(double.infinity, 48),<br>              ),<br>              child: Text(<br>                &quot;Save QR Code&quot;,<br>                style: Theme.of(context).textTheme.labelLarge?.copyWith(<br>                    color: Theme.of(context).colorScheme.onPrimaryContainer),<br>              ),<br>            ),<br>          ),<br>          Padding(<br>            padding: EdgeInsets.only(<br>              left: 16,<br>              right: 16,<br>              bottom: 16,<br>            ),<br>            child: TextButton(<br>              onPressed: () {<br>                share();<br>              },<br>              style: TextButton.styleFrom(<br>                backgroundColor:<br>                    Theme.of(context).colorScheme.surfaceContainerHighest,<br>                minimumSize: const Size(double.infinity, 48),<br>              ),<br>              child: Text(<br>                &quot;Share QR Code&quot;,<br>                style: Theme.of(context).textTheme.labelLarge?.copyWith(<br>                    color: Theme.of(context).colorScheme.onPrimaryContainer),<br>              ),<br>            ),<br>          )<br>        ],<br>      ),<br>    );<br>  }<br><br>  void share() async {<br>    try {<br>      RenderRepaintBoundary boundary = _globalKey.currentContext!<br>          .findRenderObject() as RenderRepaintBoundary;<br><br>      final image = await boundary.toImage(pixelRatio: 3.0);<br>      final byteData = await image.toByteData(format: ImageByteFormat.png);<br>      final pngBytes = byteData!.buffer.asUint8List();<br><br>      final tempDir = await getTemporaryDirectory();<br><br>      final file = File(<br>          &#39;${tempDir.path}/qr_code_${DateTime.now().millisecondsSinceEpoch}.png&#39;);<br><br>      await file.writeAsBytes(pngBytes);<br><br>      await SharePlus.instance.share(ShareParams(<br>        files: [XFile(file.path)],<br>        text: &#39;QR code&#39;,<br>      ));<br><br>      await file.delete();<br>    } catch (e) {<br>      WidgetsBinding.instance.addPostFrameCallback((_) {<br>        ScaffoldMessenger.of(context)<br>            .showSnackBar(SnackBar(content: Text(e.toString())));<br>      });<br>    }<br>  }<br><br>  void save() async {<br>    try {<br>      RenderRepaintBoundary boundary = _globalKey.currentContext!<br>          .findRenderObject() as RenderRepaintBoundary;<br><br>      final image = await boundary.toImage(pixelRatio: 3.0);<br>      final byteData = await image.toByteData(format: ImageByteFormat.png);<br>      final pngBytes = byteData!.buffer.asUint8List();<br><br>      await Gal.putImageBytes(pngBytes, album: &#39;QR Codes&#39;);<br><br>      WidgetsBinding.instance.addPostFrameCallback((_) {<br>        ScaffoldMessenger.of(context)<br>            .showSnackBar(SnackBar(content: Text(&quot;QR code saved to gallery&quot;)));<br>      });<br>    } catch (e) {<br>      WidgetsBinding.instance.addPostFrameCallback((_) {<br>        ScaffoldMessenger.of(context)<br>            .showSnackBar(SnackBar(content: Text(e.toString())));<br>      });<br>    }<br>  }<br>}</pre><p>This screen uses the mobile_scanner package to scan QR codes in real time. When a QR code is detected, its content is displayed in a text at the bottom.</p><pre>class QRCodeScannerScreen extends StatefulWidget {<br>  const QRCodeScannerScreen({super.key});<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() {<br>    return _QRCodeScannerScreen();<br>  }<br>}<br><br>class _QRCodeScannerScreen extends State&lt;QRCodeScannerScreen&gt; {<br>  String _result = &quot;&quot;;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Stack(<br>        children: [<br>          MobileScanner(onDetect: (capture) {<br>            final List&lt;Barcode&gt; barcodes = capture.barcodes;<br>            for (final barcode in barcodes) {<br>              setState(() {<br>                _result = barcode.rawValue ?? &quot;No Data found in QR&quot;;<br>              });<br>            }<br>          }),<br>          Padding(<br>            padding: EdgeInsets.all(16),<br>            child: Align(<br>              alignment: Alignment.center,<br>              child: Container(<br>                height: MediaQuery.of(context).size.width,<br>                width: MediaQuery.of(context).size.width,<br>                decoration: BoxDecoration(<br>                  borderRadius: BorderRadius.circular(16),<br>                  border: Border.all(<br>                    color: Theme.of(context).colorScheme.primaryContainer,<br>                    width: 4,<br>                  ),<br>                ),<br>              ),<br>            ),<br>          ),<br>          if (_result != &quot;&quot;)<br>            Padding(<br>              padding: EdgeInsets.all(16),<br>              child: Align(<br>                alignment: Alignment.bottomCenter,<br>                child: Card(<br>                  child: Padding(<br>                    padding: EdgeInsets.all(16),<br>                    child: SelectableText(<br>                      _result,<br>                      style: isValidLink(_result)<br>                          ? const TextStyle(color: Colors.blue)<br>                          : const TextStyle(),<br>                    ),<br>                  ),<br>                ),<br>              ),<br>            ),<br>        ],<br>      ),<br>    );<br>  }<br><br>  bool isValidLink(String input) {<br>    final uri = Uri.tryParse(input);<br>    return uri != null &amp;&amp;<br>        (uri.hasScheme &amp;&amp; (uri.scheme == &#39;http&#39; || uri.scheme == &#39;https&#39;)) &amp;&amp;<br>        uri.host.isNotEmpty;<br>  }<br>}</pre><h3>Happy coding!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95a5722d0be2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Android BLE App to Communicate with ESP32]]></title>
            <link>https://medium.com/@srkan/building-an-android-ble-app-to-communicate-with-esp32-015d6158d78e?source=rss-3bf919b049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/015d6158d78e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[bluetooth-low-energy]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Serkan]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 20:37:30 GMT</pubDate>
            <atom:updated>2024-12-14T08:49:43.585Z</atom:updated>
            <content:encoded><![CDATA[<p>Bluetooth Low Energy (BLE) has become a vital communication technology for modern IoT applications, enabling devices to exchange data efficiently while consuming minimal power. The ESP32 microcontroller, with its built-in BLE capabilities, offers a versatile platform for building innovative projects. In this article, I’ll walk you through creating an Android app that communicates with an ESP32 via BLE.</p><h3>Project Overview</h3><p>When the client connects, the BLE server generates a random number, which the Android app collects. Additionally, the Android app sends text data to the BLE server.</p><h3>Here is the source code</h3><p><a href="https://github.com/serkan-y38/Android-BLE-ESP32-Example"><em>https://github.com/serkan-y38/Android-BLE-ESP32-Example</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctWDLlJG5VPN_Vg5pzH4cg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTfknz_o2uVgKlB3nfWXkw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*DOxDAc6seZUskpc4XAY0mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1aA1_09OoHw5Zi4Rgr7fA.jpeg" /></figure><h3>Prerequisites</h3><p>Before we begin, I assume you have the following set up:</p><ol><li><strong>Android Studio</strong> installed with the required Android SDKs.</li><li><strong>Arduino IDE</strong> installed and configured with the ESP32 board support package.</li><li>An ESP32 device connected to your computer and ready for programming.</li><li>Basic knowledge of Android development and working with microcontrollers.</li></ol><h3>Lets start with writing some C++</h3><p>Open arduino ide and write below the code, then upload it. Our esp32 is ready.</p><h4>What Does This Code Do?</h4><p>This code configures an ESP32 device as a Bluetooth Low Energy (BLE) server. The server creates a BLE service with a characteristic that supports notification, reading, and writing. Here’s a step-by-step breakdown:</p><p><strong>Include BLE Libraries: </strong>The code starts by including essential BLE libraries:</p><ul><li>BLEDevice.h to manage the BLE device.</li><li>BLEServer.h to create and manage a BLE server.</li><li>BLEUtils.h for utility functions.</li><li>BLE2902.h to support notifications.</li></ul><p><strong>Define UUIDs:</strong></p><ul><li>SERVICE_UUID: A unique identifier for the BLE service.</li><li>CHARACTERISTIC_UUID: A unique identifier for the characteristic within the service.</li></ul><p><strong>Create a Server:</strong></p><ul><li>The BLEDevice::init(&quot;ESP32&quot;) initializes the BLE device with the name &quot;ESP32&quot;.</li><li>A BLE server is created and configured to handle connection and disconnection events using MyServerCallbacks.</li></ul><p><strong>Handle Connections and Disconnections:</strong></p><ul><li>The MyServerCallbacks class prints messages to the Serial Monitor when a device connects or disconnects.</li><li>When disconnected, it restarts advertising, making the ESP32 discoverable again.</li></ul><p><strong>Create a BLE Service and Characteristic:</strong></p><ul><li>A BLE service is created with the specified SERVICE_UUID.</li><li>A BLE characteristic is added to the service, supporting:</li><li><strong>Notify</strong>: Sends updates to connected clients.</li><li><strong>Read</strong>: Allows clients to read the characteristic’s value.</li><li><strong>Write</strong>: Allows clients to write data to the characteristic.</li></ul><p><strong>Handle Characteristic Writes:</strong></p><ul><li>The CharacteristicCallback class defines an action for when a client writes data to the characteristic.</li><li>It prints the received value to the Serial Monitor.</li></ul><p><strong>Advertise the Service:</strong></p><ul><li>The BLEAdvertising object broadcasts the BLE service, allowing clients to discover and connect to the ESP32.</li></ul><p><strong>Main Functionality in Loop:</strong></p><ul><li>Once a device connects, the loop() function:</li><li>Generates a random number between 0 and 100.</li><li>Converts the number to a string and sends it as a notification to the connected client using pCharacteristic-&gt;notify().</li><li>Prints the sent value to the Serial Monitor.</li><li>The process repeats every second (delay(1000)).</li></ul><pre>#include &lt;BLEDevice.h&gt;<br>#include &lt;BLEServer.h&gt;<br>#include &lt;BLEUtils.h&gt;<br>#include &lt;BLE2902.h&gt;<br><br>BLECharacteristic *pCharacteristic;<br>bool deviceConnected = false;<br><br>#define SERVICE_UUID &quot;22bf526e-1f59-40fb-a344-0bea8c1bfef2&quot;<br>#define CHARACTERISTIC_UUID &quot;cdc7651d-88bd-4c0d-8c90-4572db5aa14b&quot;<br><br>class MyServerCallbacks: public BLEServerCallbacks { <br>  void onConnect(BLEServer* pServer){<br>    Serial.println(&quot;connected&quot;);<br>    deviceConnected = true;<br>  };<br><br>  void onDisconnect(BLEServer *pServer){<br>    deviceConnected = false;<br>    <br>    Serial.println(&quot;disconnected&quot;);<br>    delay(500); <br><br>    pServer-&gt;getAdvertising()-&gt;start();  <br>    Serial.println(&quot;waiting for connection from client&quot;);<br>  }<br>};<br><br>class CharacteristicCallback : public BLECharacteristicCallbacks {<br>  void onWrite(BLECharacteristic* dhtCharacteristic) {<br>    String value = pCharacteristic-&gt;getValue();<br>    Serial.print(&quot;Received Value: &quot;);<br>    Serial.println(value.c_str());  <br>  }<br>};<br><br><br>void initialize(){<br>  Serial.begin(9600);<br>  <br>  BLEDevice::init(&quot;ESP32&quot;);<br><br>  BLEServer *pServer = BLEDevice::createServer();<br>  pServer-&gt;setCallbacks(new MyServerCallbacks());<br><br>  BLEService *pService = pServer-&gt;createService(SERVICE_UUID);  <br><br>  pCharacteristic = pService-&gt;createCharacteristic(<br>    CHARACTERISTIC_UUID,<br>    BLECharacteristic::PROPERTY_NOTIFY | <br>    BLECharacteristic::PROPERTY_READ | <br>    BLECharacteristic::PROPERTY_WRITE<br>  );<br><br>  pCharacteristic-&gt;addDescriptor(new BLE2902());<br>  pCharacteristic-&gt;setCallbacks(new CharacteristicCallback());<br><br>  pService-&gt;start();<br><br>  BLEAdvertising* pAdvertising = BLEDevice::getAdvertising();<br>  pAdvertising-&gt;addServiceUUID(SERVICE_UUID);<br>  pAdvertising-&gt;setScanResponse(true);<br>  pAdvertising-&gt;setMinPreferred(0x12);<br>  <br>  pServer-&gt;getAdvertising()-&gt;start();<br><br>  Serial.println(&quot;waiting for connection from client&quot;);<br>}<br><br>void setup() {<br>  initialize();<br>}<br><br>void loop() {<br>  if (deviceConnected) {<br>    int randomNumber = random(0, 100);<br>    char txString[8];<br><br>    dtostrf(randomNumber, 1, 2, txString);<br><br>    pCharacteristic-&gt;setValue(txString);  <br>    pCharacteristic-&gt;notify();<br><br>    Serial.print(&quot;sent value: &quot;);<br>    Serial.println(randomNumber);<br><br>    delay(1000);<br>  }<br>}</pre><h3>Lets Dive Into Android</h3><p>I won’t share the entire source code here. Please visit the link above to access the complete source code. Below, I’ll explain the basic functions and their implementations.</p><pre>interface BLEController {<br>    val scannedDevices: StateFlow&lt;List&lt;BluetoothDeviceModel&gt;&gt;<br>    val pairedDevices: StateFlow&lt;List&lt;BluetoothDeviceModel&gt;&gt;<br>    val receivedValues: StateFlow&lt;List&lt;String&gt;&gt;<br><br>    val message: SharedFlow&lt;String&gt;<br>    val isConnected: StateFlow&lt;Boolean&gt;<br>    val isPairing: StateFlow&lt;Boolean&gt;<br>    val connectedDeviceName: StateFlow&lt;String&gt;<br><br>    fun startScan()<br><br>    fun stopScan()<br><br>    fun release()<br><br>    fun pair(address: String)<br><br>    fun connect(address: String)<br><br>    fun disConnect()<br><br>    fun sendValue(text: String)<br>}</pre><pre>@SuppressLint(&quot;MissingPermission&quot;)<br>class BLEControllerImpl(<br>    private val context: Context<br>) : BLEController {<br><br>    private val bluetoothManager by lazy {<br>        context.getSystemService(BluetoothManager::class.java)<br>    }<br><br>    private val bluetoothAdapter by lazy {<br>        bluetoothManager?.adapter<br>    }<br><br>    private var isScanning = false<br>    private var isPairDeviceReceiverRegistered = false<br>    private var bluetoothGatt: BluetoothGatt? = null<br><br>    private val _scannedDevices = MutableStateFlow&lt;List&lt;BluetoothDeviceModel&gt;&gt;(emptyList())<br>    override val scannedDevices: StateFlow&lt;List&lt;BluetoothDeviceModel&gt;&gt;<br>        get() = _scannedDevices.asStateFlow()<br><br>    private val _pairedDevices = MutableStateFlow&lt;List&lt;BluetoothDeviceModel&gt;&gt;(emptyList())<br>    override val pairedDevices: StateFlow&lt;List&lt;BluetoothDeviceModel&gt;&gt;<br>        get() = _pairedDevices.asStateFlow()<br><br>    private val _receivedValues = MutableStateFlow&lt;List&lt;String&gt;&gt;(emptyList())<br>    override val receivedValues: StateFlow&lt;List&lt;String&gt;&gt;<br>        get() = _receivedValues.asStateFlow()<br><br>    private val _message = MutableSharedFlow&lt;String&gt;()<br>    override val message: SharedFlow&lt;String&gt;<br>        get() = _message.asSharedFlow()<br><br>    private val _isConnected = MutableStateFlow(false)<br>    override val isConnected: StateFlow&lt;Boolean&gt;<br>        get() = _isConnected.asStateFlow()<br><br>    private val _isPairing = MutableStateFlow(false)<br>    override val isPairing: StateFlow&lt;Boolean&gt;<br>        get() = _isPairing.asStateFlow()<br><br>    private val _connectedDeviceName = MutableStateFlow(&quot;&quot;)<br>    override val connectedDeviceName: StateFlow&lt;String&gt;<br>        get() = _connectedDeviceName.asStateFlow()<br><br>    private val leScanCallback: ScanCallback = object : ScanCallback() {<br>        override fun onScanResult(callbackType: Int, result: ScanResult) {<br>            super.onScanResult(callbackType, result)<br>            _scannedDevices.update { devices -&gt;<br>                val newDevice = result.device.toBluetoothDeviceModel()<br>                if (newDevice in devices) devices else devices + newDevice<br>            }<br>        }<br>    }<br><br>    private val pairDeviceReceiver = PairDeviceReceiver(<br>        onPairRequest = {<br>            _isPairing.update { true }<br>            Log.i(&quot;PairDeviceReceiver&quot;, &quot;Pairing request sent&quot;)<br>        },<br>        onPairedSuccessfully = { device -&gt;<br>            setMessage(&quot;Connected to ${device?.address}&quot;)<br><br>            stopScan()<br>            getPairedDevices()<br><br>            _scannedDevices.update { emptyList() }<br>            _isPairing.update { false }<br>        },<br>        onPairingError = { device -&gt;<br>            setMessage(&quot;Cannot connected to device ${device?.address}&quot;)<br><br>            stopScan()<br><br>            _scannedDevices.update { emptyList() }<br>            _isPairing.update { false }<br>        },<br>        onPairing = {<br>            _isPairing.update { true }<br>        }<br>    )<br><br>    private val gattCallback = object : BluetoothGattCallback() {<br><br>        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {<br>            if (status == BluetoothGatt.GATT_SUCCESS) {<br>                if (newState == BluetoothProfile.STATE_CONNECTED) {<br>                    setMessage(&quot;Successfully connected to ${gatt.device.address}&quot;)<br>                    _isConnected.update { true }<br>                    _connectedDeviceName.update { gatt.device.name }<br>                    gatt.discoverServices()<br><br>                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {<br>                    setMessage(&quot;Successfully disconnected from ${gatt.device.address}&quot;)<br>                    _isConnected.update { false }<br>                    _connectedDeviceName.update { &quot;&quot; }<br>                    gatt.close()<br>                }<br><br>            } else {<br>                setMessage(&quot;Error $status encountered for ${gatt.device.address}&quot;)<br>                _isConnected.update { false }<br>                _connectedDeviceName.update { &quot;&quot; }<br>                gatt.close()<br>            }<br>        }<br><br>        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {<br>            if (status == BluetoothGatt.GATT_SUCCESS) {<br>                gatt.getService(UUID.fromString(SERVICE_UUID)).let { service -&gt;<br><br>                    val characteristic =<br>                        service.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID))<br><br>                    if (characteristic != null) {<br>                        gatt.setCharacteristicNotification(characteristic, true)<br><br>                        val descriptor = characteristic.getDescriptor(<br>                            UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG_UUID)<br>                        )<br>                        descriptor?.let {<br>                            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>                                gatt.writeDescriptor(<br>                                    it,<br>                                    BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE<br>                                )<br>                            } else {<br>                                @Suppress(&quot;DEPRECATION&quot;)<br>                                it.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE<br>                                @Suppress(&quot;DEPRECATION&quot;)<br>                                gatt.writeDescriptor(it)<br>                            }<br>                        }<br>                    } else {<br>                        setMessage(&quot;Characteristic not found!&quot;)<br>                    }<br><br>                } ?: run {<br>                    setMessage(&quot;Service not found!&quot;)<br>                }<br>            } else {<br>                setMessage(&quot;Service discovery failed -&gt; status: $status&quot;)<br>            }<br>        }<br><br>        override fun onCharacteristicChanged(<br>            gatt: BluetoothGatt,<br>            characteristic: BluetoothGattCharacteristic,<br>            value: ByteArray<br>        ) {<br>            super.onCharacteristicChanged(gatt, characteristic, value)<br>            if (characteristic.uuid == UUID.fromString(CHARACTERISTIC_UUID)) {<br>                @Suppress(&quot;DEPRECATION&quot;)<br>                val receivedValue = characteristic.value?.let { byteArray -&gt;<br>                    String(byteArray, Charsets.UTF_8)<br>                } ?: &quot;No value received&quot;<br><br>                _receivedValues.update { values -&gt;<br>                    values + receivedValue<br>                }<br>            }<br>        }<br><br>        override fun onCharacteristicWrite(<br>            gatt: BluetoothGatt?,<br>            characteristic: BluetoothGattCharacteristic?,<br>            status: Int<br>        ) {<br>            super.onCharacteristicWrite(gatt, characteristic, status)<br>            if (status == BluetoothGatt.GATT_SUCCESS) {<br>                setMessage(&quot;Value sent successfully to server: ${gatt?.device?.address}&quot;)<br>            } else {<br>                setMessage(&quot;Failed to send value -&gt; status: $status&quot;)<br>            }<br>        }<br>    }<br><br>    init {<br>        getPairedDevices()<br>    }<br><br>    override fun startScan() {<br>        if (!hasBluetoothScanPermission()) {<br>            setMessage(&quot;No bluetooth permission&quot;)<br>            return<br>        }<br><br>        if (!isBluetoothEnabled()) {<br>            setMessage(&quot;Bluetooth not enabled&quot;)<br>            return<br>        }<br><br>        if (isScanning) return<br><br>        if (!isPairDeviceReceiverRegistered) {<br>            registerPairDeviceReceiver()<br>            isPairDeviceReceiverRegistered = true<br>        }<br><br>        getPairedDevices()<br><br>        bluetoothAdapter?.bluetoothLeScanner?.startScan(leScanCallback)<br>        isScanning = true<br>    }<br><br>    @SuppressLint(&quot;MissingPermission&quot;)<br>    override fun stopScan() {<br>        if (!hasBluetoothScanPermission()) {<br>            setMessage(&quot;No bluetooth permission&quot;)<br>            return<br>        }<br><br>        if (!isBluetoothEnabled()) {<br>            setMessage(&quot;Bluetooth not enabled&quot;)<br>            return<br>        }<br><br>        if (!isScanning) return<br><br>        bluetoothAdapter?.bluetoothLeScanner?.stopScan(leScanCallback)<br>        _scannedDevices.update { emptyList() }<br>        isScanning = false<br>    }<br><br>    override fun release() {<br>        disConnect()<br><br>        if (isPairDeviceReceiverRegistered) context.unregisterReceiver(pairDeviceReceiver)<br>    }<br><br>    override fun pair(address: String) {<br>        if (!hasBluetoothConnectPermission()) return<br>        val device = bluetoothAdapter?.getRemoteDevice(address)<br><br>        device?.let {<br>            try {<br>                device.createBond()<br>            } catch (e: Exception) {<br>                setMessage((&quot;Failed to pair with device: ${e.message}&quot;))<br>            }<br>        } ?: run {<br>            setMessage(&quot;Device not found with address: $address&quot;)<br>        }<br>    }<br><br>    override fun connect(address: String) {<br>        val device = bluetoothAdapter?.getRemoteDevice(address)<br>        bluetoothGatt = device?.connectGatt(context, false, gattCallback, TRANSPORT_LE)<br><br>        stopScan()<br>    }<br><br>    override fun disConnect() {<br>        bluetoothGatt?.disconnect()<br>        bluetoothGatt?.close()<br><br>        _isConnected.update { false }<br>        _connectedDeviceName.update { &quot;&quot; }<br>        _receivedValues.update { emptyList() }<br><br>        setMessage(&quot;Successfully disconnected from ${bluetoothGatt?.device?.address}&quot;)<br>    }<br><br>    override fun sendValue(text: String) {<br>        val service = bluetoothGatt?.getService(UUID.fromString(SERVICE_UUID))<br>        val characteristic = service?.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID))<br><br>        characteristic?.let {<br>            val data = text.toByteArray(Charsets.UTF_8)<br>            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>                bluetoothGatt?.writeCharacteristic(<br>                    it,<br>                    data,<br>                    BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT<br>                )<br>            } else {<br>                @Suppress(&quot;DEPRECATION&quot;)<br>                it.value = data<br>                @Suppress(&quot;DEPRECATION&quot;)<br>                bluetoothGatt?.writeCharacteristic(it)<br>            }<br>        } ?: run {<br>            setMessage(&quot;Characteristic not found!&quot;)<br>        }<br>    }<br><br>    private fun getPairedDevices() {<br>        if (!hasBluetoothConnectPermission()) {<br>            setMessage(&quot;No BLUETOOTH_CONNECT permission&quot;)<br>            return<br>        }<br><br>        bluetoothAdapter<br>            ?.bondedDevices<br>            ?.map { it.toBluetoothDeviceModel() }<br>            ?.also { devices -&gt; _pairedDevices.update { devices } }<br>    }<br><br>    private fun registerPairDeviceReceiver() {<br>        context.registerReceiver(<br>            pairDeviceReceiver,<br>            IntentFilter().apply {<br>                addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)<br>                addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)<br>            }<br>        )<br>    }<br><br>    private fun hasBluetoothScanPermission(): Boolean {<br>        var hasPermission = true<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) {<br>            if (!hasPermission(Manifest.permission.BLUETOOTH_SCAN)) {<br>                hasPermission = false<br>            }<br>        } else {<br>            if (!hasPermission(Manifest.permission.BLUETOOTH)) {<br>                hasPermission = false<br>            }<br>        }<br>        return hasPermission<br>    }<br><br>    private fun hasBluetoothConnectPermission(): Boolean {<br>        var hasPermission = true<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) {<br>            if (!hasPermission(Manifest.permission.BLUETOOTH_CONNECT)) {<br>                hasPermission = false<br>            }<br>        } else {<br>            if (!hasPermission(Manifest.permission.BLUETOOTH)) {<br>                hasPermission = false<br>            }<br>        }<br>        return hasPermission<br>    }<br><br>    private fun isBluetoothEnabled() = bluetoothAdapter?.isEnabled == true<br><br>    private fun setMessage(text: String) {<br>        CoroutineScope(Dispatchers.IO).launch {<br>            _message.emit(text)<br>        }<br>    }<br><br>    private fun hasPermission(permission: String) =<br>        context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED<br><br>    companion object {<br>        private const val SERVICE_UUID = &quot;22bf526e-1f59-40fb-a344-0bea8c1bfef2&quot;<br>        private const val CHARACTERISTIC_UUID = &quot;cdc7651d-88bd-4c0d-8c90-4572db5aa14b&quot;<br>        private const val CLIENT_CHARACTERISTIC_CONFIG_UUID = &quot;00002902-0000-1000-8000-00805f9b34fb&quot;<br>    }<br>}</pre><p>This comprehensive BLEController interface and its BLEControllerImpl implementation for Android provide the necessary functionality to interact with Bluetooth Low Energy (BLE) devices effectively. Here&#39;s a quick breakdown:</p><p><strong>StateFlow Properties</strong>:</p><ul><li>scannedDevices, pairedDevices, receivedValues: Real-time updates on BLE devices and received data.</li><li>isConnected, isPairing, connectedDeviceName: Track the state of the connection and pairing status.</li></ul><p><strong>SharedFlow Property</strong>:</p><ul><li>message: Emit messages for status or errors.</li></ul><p><strong>Functions</strong>:</p><ul><li>startScan, stopScan, pair, connect, disConnect, sendValue: Core BLE operations.</li><li>release: Clean up resources.</li></ul><p><strong>Permissions Handling</strong>: Adapts to API level changes (e.g., BLUETOOTH_SCAN, BLUETOOTH_CONNECT introduced in API 31).</p><p><strong>UUID Constants</strong>:</p><ul><li>SERVICE_UUID and CHARACTERISTIC_UUID need to match your BLE device&#39;s specifications.</li></ul><p><strong>Threading</strong>:</p><ul><li>Uses CoroutineScope for emitting messages and maintaining thread safety.</li></ul><p><strong>BLE Scanning and Pairing</strong>:</p><ul><li>Starts/stops BLE scans with startScan and stopScan.</li><li>Implements a PairDeviceReceiver to handle pairing callbacks.</li><li>Uses MutableStateFlow to manage and update device lists dynamically.</li></ul><p><strong>BLE Connection Management</strong>:</p><ul><li>Connects to BLE devices with connect and handles BluetoothGattCallback for connection and service discovery.</li><li>Supports characteristic notifications and value changes.</li></ul><p><strong>Data Communication</strong>:</p><ul><li>sendValue: Sends data to BLE devices using GATT characteristics.</li><li>Handles value updates via onCharacteristicChanged.</li></ul><p><strong>Permissions</strong>:</p><ul><li>Checks for Bluetooth permissions dynamically based on API level.</li></ul><p><strong>Error Handling and Messaging</strong>:</p><ul><li>Emits detailed messages for errors or operation status through SharedFlow.</li></ul><p><strong>Resource Management</strong>:</p><ul><li>Implements release to unregister receivers and clean up BLE connections.</li></ul><h3><strong>Happy coding!</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=015d6158d78e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Migrating from Kapt to KSP for Room and Dagger Hilt in Kotlin]]></title>
            <link>https://medium.com/@srkan/a-guide-to-migrating-from-kapt-to-ksp-for-room-and-dagger-hilt-in-kotlin-f65937579fa2?source=rss-3bf919b049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f65937579fa2</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ksp]]></category>
            <category><![CDATA[kapt]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Serkan]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 06:20:53 GMT</pubDate>
            <atom:updated>2024-07-12T06:20:53.224Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding KAPT and KSP</h3><h4>What is KAPT?</h4><p>KAPT, short for Kotlin Annotation Processing Tool, is a Kotlin compiler plugin that allows annotation processors written in Java to be used in Kotlin projects. Annotation processors generate code, files, or other resources based on annotations in the source code. KAPT bridges the gap between Java annotation processors and Kotlin, making it possible to leverage Java-based libraries and tools like Dagger, Room, and Glide in Kotlin projects. Despite its utility, KAPT has some performance drawbacks, including increased compilation times and less efficient error handling, which can slow down development.</p><h4>What is KSP?</h4><p>KSP, or Kotlin Symbol Processing, is a more recent tool introduced by JetBrains to address some of the limitations of KAPT. KSP is designed specifically for Kotlin, making it more efficient and better integrated with the Kotlin compiler. It provides a simplified API for processing annotations and generating code, leading to faster compilation times and improved performance. KSP can also handle more complex use cases and offers better support for Kotlin-specific features, making it a more robust solution for annotation processing in Kotlin projects.</p><h4>Why Migrate from KAPT to KSP?</h4><p>Migrating from KAPT to KSP brings several advantages:</p><ul><li><strong>Improved Performance</strong>: KSP is optimized for Kotlin and offers significantly faster build times compared to KAPT. This can lead to a more efficient development process and reduced waiting times during compilation.</li><li><strong>Better Kotlin Integration</strong>: Since KSP is designed specifically for Kotlin, it handles Kotlin-specific features more gracefully. This means fewer issues and workarounds compared to KAPT.</li><li><strong>Enhanced Error Handling</strong>: KSP provides better error messages and diagnostics, which can help developers identify and fix issues more quickly.</li><li><strong>Simplified API</strong>: KSP’s API is more straightforward and easier to use compared to KAPT, making the codebase cleaner and easier to maintain.</li></ul><h3>Migrating kapt to ksp</h3><p>Exist <em>build.gradle.kts</em> files</p><pre>// Top-level build file where you can add configuration options common to all sub-projects/modules.<br>plugins {<br>    .<br>    .<br>    .<br>    id(&quot;com.google.dagger.hilt.android&quot;) version &quot;2.51.1&quot; apply false<br>}<br>tasks.register(&quot;clean&quot;, Delete::class) {<br>    delete(rootProject.layout.buildDirectory)<br>}</pre><pre>plugins {<br>    .<br>    .<br>    .<br>    id(&quot;com.google.dagger.hilt.android&quot;)<br>    id(&quot;kotlin-kapt&quot;)<br>}<br><br>android {<br>    .<br>    .<br>    .    <br>}<br><br>composeCompiler {<br>    .<br>    .<br>    . <br>}<br><br>dependencies {<br>    .<br>    .<br>    .<br><br>    // Dagger Hilt<br>    implementation(&quot;com.google.dagger:hilt-android:2.51.1&quot;)<br>    kapt(&quot;com.google.dagger:hilt-android-compiler:2.51.1&quot;)<br><br>    // Room<br>    implementation(&quot;androidx.room:room-runtime:2.6.1&quot;)<br>    annotationProcessor(&quot;androidx.room:room-compiler:2.6.1&quot;)<br>    //noinspection KaptUsageInsteadOfKsp<br>    kapt(&quot;androidx.room:room-compiler:2.6.1&quot;)<br>    implementation(&quot;androidx.room:room-ktx:2.6.1&quot;)<br>    testImplementation(&quot;androidx.room:room-testing:2.6.1&quot;)<br>    implementation(&quot;androidx.room:room-paging:2.6.1&quot;)<br><br>}<br><br>// Allow references to generated code<br>kapt {<br>    correctErrorTypes = true<br>}</pre><p>Updated <em>build.gradle.kts</em> files</p><pre>// Top-level build file where you can add configuration options common to all sub-projects/modules.<br>plugins {<br>       .<br>       .<br>       .<br>    id(&quot;com.google.dagger.hilt.android&quot;) version &quot;2.51.1&quot; apply false<br>    id(&quot;com.google.devtools.ksp&quot;) version &quot;2.0.0-1.0.22&quot; apply false // add<br>}<br>tasks.register(&quot;clean&quot;, Delete::class) {<br>    delete(rootProject.layout.buildDirectory)<br>}</pre><pre>plugins {<br>    .<br>    .<br>    .<br>    id(&quot;com.google.dagger.hilt.android&quot;)<br>    //id(&quot;kotlin-kapt&quot;) // remove<br>    id(&quot;com.google.devtools.ksp&quot;) // add<br>}<br><br>android {<br>    .<br>    .<br>    .    <br>}<br><br>composeCompiler {<br>    .<br>    .<br>    . <br>}<br><br>dependencies {<br>    .<br>    .<br>    .<br><br>    // Dagger Hilt<br>    implementation(&quot;com.google.dagger:hilt-android:2.51.1&quot;)<br>    //kapt(&quot;com.google.dagger:hilt-android-compiler:2.51.1&quot;) // remove<br>    ksp(&quot;com.google.dagger:hilt-android-compiler:2.51.1&quot;) // add<br>    ksp(&quot;com.google.dagger:dagger-compiler:2.51.1&quot;) // add<br><br>    // Room<br>    implementation(&quot;androidx.room:room-runtime:2.6.1&quot;)<br>    annotationProcessor(&quot;androidx.room:room-compiler:2.6.1&quot;)<br>    //noinspection KaptUsageInsteadOfKsp // remove<br>    //kapt(&quot;androidx.room:room-compiler:2.6.1&quot;) // remove<br>    ksp(&quot;androidx.room:room-compiler:2.6.1&quot;) // add<br>    implementation(&quot;androidx.room:room-ktx:2.6.1&quot;)<br>    testImplementation(&quot;androidx.room:room-testing:2.6.1&quot;)<br>    implementation(&quot;androidx.room:room-paging:2.6.1&quot;)<br><br>}<br><br>// remove kapt {} block</pre><p>To see the full implementation and explore the project files after migrating from KAPT to KSP, visit the <a href="https://github.com/serkan-y38/Android-ContinuousGoals/tree/551c593ea612b174c56effc3a646052574fed89d">GitHub repository.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f65937579fa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User Authentication with Firebase]]></title>
            <link>https://medium.com/@srkan/user-authentication-with-firebase-962ee766bed2?source=rss-3bf919b049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/962ee766bed2</guid>
            <dc:creator><![CDATA[Serkan]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 14:21:35 GMT</pubDate>
            <atom:updated>2025-04-30T06:51:30.086Z</atom:updated>
            <content:encoded><![CDATA[<h4>User Authentication with Firebase in Kotlin: A Comprehensive Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6UO_bBpGDvAkf-x4OEc8w.png" /></figure><p>Embark on a journey through modern app development as we delve into the seamless integration of Firebase Authentication in Kotlin. This article explores the synergy between cutting-edge technologies like Dagger Hilt, Kotlin Coroutines, Compose Navigation, and the robust Firebase Authentication platform. Adopting the MVVM pattern and Clean Architecture principles, we’ll navigate the intricate process of user authentication, ensuring scalability, maintainability, and optimal user experience.</p><p><a href="https://github.com/serkan-y38">https://github.com/serkan-y38</a></p><h4>Step-by-Step Guide:</h4><p><strong>Step 1:</strong> Create a new empty Jetpack Compose project</p><p><strong>Step 2:</strong> Add the following dependencies:</p><pre>[versions]<br>.<br>.<br>.<br>googleServices = &quot;4.4.1&quot;<br>firebaseAuth = &quot;22.3.1&quot;<br>daggerHilt = &quot;2.50&quot;<br>navigation = &quot;2.8.0-alpha04&quot;<br>hiltNavigation = &quot;1.2.0&quot;<br>coroutines = &quot;1.8.0&quot;<br><br>[libraries]<br>.<br>.<br>.<br>google-services = { group = &quot;com.google.gms&quot;, name = &quot;google-services&quot;, version.ref = &quot;googleServices&quot; }<br>firebase-auth = { group = &quot;com.google.firebase&quot;, name = &quot;firebase-auth&quot;, version.ref = &quot;firebaseAuth&quot; }<br>hilt-android-compiler = { group = &quot;com.google.dagger&quot;, name = &quot;hilt-android-compiler&quot;, version.ref = &quot;daggerHilt&quot; }<br>hilt-android = { group = &quot;com.google.dagger&quot;, name = &quot;hilt-android&quot;, version.ref = &quot;daggerHilt&quot; }<br>navigation-compose = { group = &quot;androidx.navigation&quot;, name = &quot;navigation-compose&quot;, version.ref = &quot;navigation&quot; }<br>hilt-navigation-compose = { group = &quot;androidx.hilt&quot;, name = &quot;hilt-navigation-compose&quot;, version.ref = &quot;hiltNavigation&quot; }<br>kotlinx-coroutines-android = { module = &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android&quot;, version.ref = &quot;coroutines&quot; }<br><br>[plugins]<br>.<br>.<br>.<br>org-jetbrains-kotlin-kapt = { id = &quot;org.jetbrains.kotlin.kapt&quot;, version.ref = &quot;kotlin&quot; }<br>daggerHilt = { id = &quot;com.google.dagger.hilt.android&quot;, version.ref = &quot;daggerHilt&quot; }</pre><pre>buildscript {<br>    dependencies {<br>        classpath(libs.google.services)<br>    }<br>}<br>// Top-level build file where you can add configuration options common to all sub-projects/modules.<br>plugins {<br>    .<br>    .<br>    .<br>    alias(libs.plugins.daggerHilt) apply false<br>    alias(libs.plugins.org.jetbrains.kotlin.kapt) apply false<br>}<br>tasks.register(&quot;clean&quot;, Delete::class) {<br>    delete(project.layout.buildDirectory)<br>}</pre><pre>plugins {<br>    .<br>    .<br>    .<br>    alias(libs.plugins.daggerHilt)<br>    alias(libs.plugins.org.jetbrains.kotlin.kapt)<br>    id(&quot;com.google.gms.google-services&quot;)<br>}<br><br>android {<br>    .<br>    .<br>    .<br>}<br><br>dependencies {<br>    .<br>    .<br>    .<br><br>    implementation(libs.hilt.android)<br>    kapt(libs.hilt.android.compiler)<br>    implementation(libs.kotlinx.coroutines.android)<br>    implementation(libs.navigation.compose)<br>    implementation(libs.hilt.navigation.compose)<br>}<br>// Allow references to generated code<br>kapt {<br>    correctErrorTypes = true<br>}</pre><p><strong>Step 3:</strong> Connect your project to firebase then enable Email/Password provider</p><p><strong>Step 4: </strong>Let’s code</p><p>Create <em>Response </em>class under <em>core </em>package.</p><pre>sealed class Response&lt;out T&gt; {<br>    data object Loading : Response&lt;Nothing&gt;()<br>    data class Success&lt;out T&gt;(val data: T) : Response&lt;T&gt;()<br>    data class Error(val message: String) : Response&lt;Nothing&gt;()<br>}</pre><p>Create <em>AuthenticationRepository </em>interface under <em>domain/repository</em> package.</p><pre>interface AuthenticationRepository {<br><br>    suspend fun login(email: String, password: String): Flow&lt;Response&lt;AuthResult&gt;&gt;<br><br>    suspend fun register(email: String, password: String): Flow&lt;Response&lt;AuthResult&gt;&gt;<br><br>    suspend fun resetPassword(email: String): Flow&lt;Response&lt;Void?&gt;&gt;<br><br>    suspend fun logout()<br><br>    suspend fun userUid(): String<br><br>    suspend fun isLoggedIn(): Boolean<br><br>}</pre><p>Create <em>AuthenticationRepositoryImpl </em>class under <em>data/repository</em> package.</p><pre>class AuthenticationRepositoryImpl @Inject constructor(<br>    private val auth: FirebaseAuth<br>) : AuthenticationRepository {<br><br>    override suspend fun userUid(): String = auth.currentUser?.uid ?: &quot;&quot;<br><br>    override suspend fun isLoggedIn(): Boolean = auth.currentUser == null<br><br>    override suspend fun logout() = auth.signOut()<br><br>    override suspend fun login(email: String, password: String): Flow&lt;Response&lt;AuthResult&gt;&gt; = flow {<br>        try {<br>            emit(Response.Loading)<br>            val data = auth.signInWithEmailAndPassword(email, password).await()<br>            emit(Response.Success(data))<br>        } catch (e: Exception) {<br>            emit(Response.Error(e.localizedMessage ?: &quot;Oops, something went wrong.&quot;))<br>        }<br>    }<br><br>    override suspend fun register(email: String, password: String): Flow&lt;Response&lt;AuthResult&gt;&gt; =<br>        flow {<br>            try {<br>                emit(Response.Loading)<br>                val data = auth.createUserWithEmailAndPassword(email, password).await()<br>                emit(Response.Success(data))<br>            } catch (e: Exception) {<br>                emit(Response.Error(e.localizedMessage ?: &quot;Oops, something went wrong.&quot;))<br>            }<br>        }<br><br>    override suspend fun resetPassword(email: String): Flow&lt;Response&lt;Void?&gt;&gt; = flow {<br>        try {<br>            emit(Response.Loading)<br>            val data = auth.sendPasswordResetEmail(email).await()<br>            emit(Response.Success(data))<br>        } catch (e: Exception) {<br>            emit(Response.Error(e.localizedMessage ?: &quot;Oops, something went wrong.&quot;))<br>        }<br>    }<br><br>}</pre><p>Create <em>AuthenticationModule </em>under <em>di </em>package.</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object AuthenticationModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideFirebaseAuth(): FirebaseAuth = FirebaseAuth.getInstance()<br><br>    @Provides<br>    @Singleton<br>    fun provideAuthenticationRepository(<br>        auth: FirebaseAuth<br>    ): AuthenticationRepository = AuthenticationRepositoryImpl(auth)<br><br>}</pre><p>Create <em>MyApplication </em>class.</p><pre>@HiltAndroidApp<br>class MyApplication : Application()</pre><p>Update <em>AndroidManifest </em>file.</p><pre>&lt;application<br>    android:name=&quot;.MyApplication&quot;<br>    .<br>    .<br>    .<br>    &lt;activity<br>        .<br>        .<br>        .<br>    &lt;/activity&gt;<br>&lt;/application&gt;</pre><p>Create <em>use cases</em> under <em>domain/usecase/auth</em> package</p><pre>class ResetPasswordUseCase @Inject constructor(<br>    private val authenticationRepository: AuthenticationRepository<br>) {<br>    suspend operator fun invoke(email: String) = authenticationRepository.resetPassword(email)<br>}</pre><pre>class RegisterUseCase @Inject constructor(<br>    private val authenticationRepository: AuthenticationRepository<br>) {<br>    suspend operator fun invoke(email: String, password: String) =<br>        authenticationRepository.register(email, password)<br>}</pre><pre>class LogoutUseCase @Inject constructor(<br>    private val authenticationRepository: AuthenticationRepository<br>) {<br>    suspend operator fun invoke() = authenticationRepository.logout()<br>}</pre><pre>class LoginUseCase @Inject constructor(<br>    private val authenticationRepository: AuthenticationRepository<br>) {<br>    suspend operator fun invoke(email: String, password: String) =<br>        authenticationRepository.login(email, password)<br>}</pre><pre>class IsLoggedInUseCase @Inject constructor(<br>    private val authenticationRepository: AuthenticationRepository<br>) {<br>    operator fun invoke() = flow { emit(authenticationRepository.isLoggedIn()) }<br>}</pre><pre>class GetUserUidUseCase @Inject constructor(<br>    private val authenticationRepository: AuthenticationRepository<br>  ) {<br>    suspend operator fun invoke() = flow { emit(authenticationRepository.userUid()) }<br>}</pre><p>Create common ui elements under <em>presentation/screen/common</em> package</p><pre>@Composable<br>fun MyAlertDialog(<br>    onDismissRequest: () -&gt; Unit,<br>    onConfirmation: () -&gt; Unit,<br>    title: String,<br>    text: String,<br>    confirmButtonText: String,<br>    dismissButtonText: String,<br>    cancelable: Boolean<br>) {<br>    AlertDialog(<br>        title = { Text(text = title) },<br>        text = { Text(text = text) },<br>        onDismissRequest = { onDismissRequest() },<br>        confirmButton = {<br>            TextButton(<br>                onClick = { onConfirmation() }<br>            ) {<br>                Text(confirmButtonText)<br>            }<br>        },<br>        dismissButton = {<br>            TextButton(<br>                onClick = { onDismissRequest() }<br>            ) {<br>                Text(dismissButtonText)<br>            }<br>        },<br>        properties = DialogProperties(<br>            dismissOnBackPress = cancelable,<br>            dismissOnClickOutside = cancelable,<br>        )<br>    )<br>}</pre><pre>@Composable<br>fun MyCircularProgress() {<br>    Box(modifier = Modifier.fillMaxSize()) {<br>        CircularProgressIndicator(<br>            modifier = Modifier<br>                .width(64.dp)<br>                .align(Center),<br>            color = MaterialTheme.colorScheme.secondary,<br>            trackColor = MaterialTheme.colorScheme.surfaceVariant,<br>        )<br>    }<br>}</pre><p>Create <em>HomeScreen </em>and <em>HomeViewModel </em>classes under <em>presentation/screen/home </em>package</p><pre>@Composable<br>fun HomeScreen(<br>    navHostController: NavHostController,<br>    homeViewModel: HomeViewModel = hiltViewModel()<br>) {<br>    Box(modifier = Modifier.fillMaxSize()) {<br>        Button(<br>            onClick = {<br>                homeViewModel.logout()<br>                navHostController.navigate(NavigationGraph.LoginScreen.route) { popUpTo(0) }<br>            },<br>            modifier = Modifier<br>                .wrapContentSize()<br>                .align(Alignment.Center)<br>        ) {<br>            Text(text = &quot;Logout&quot;)<br>        }<br>    }<br>}</pre><pre>@HiltViewModel<br>class HomeViewModel @Inject constructor(<br>    private val logoutUseCase: LogoutUseCase<br>) : ViewModel() {<br><br>    fun logout() = viewModelScope.launch {<br>        logoutUseCase.invoke()<br>    }<br><br>}</pre><p>Create <em>LoginScreen </em>and <em>LoginViewModel </em>classes under <em>presentation/screen/login</em> package</p><pre>@Composable<br>fun LoginScreen(<br>    navHostController: NavHostController = rememberNavController(),<br>    loginViewModel: LoginViewModel = hiltViewModel()<br>) {<br>    val hostState = remember {<br>        SnackbarHostState()<br>    }<br><br>    Scaffold(<br>        snackbarHost = { SnackbarHost(hostState = hostState) },<br>        modifier = Modifier.fillMaxSize()<br>    ) { paddingValues -&gt;<br>        Content(<br>            hostState = hostState,<br>            paddingValues = paddingValues,<br>            signInStateFlow = loginViewModel.loginFlow,<br>            resetPasswordStateFlow = loginViewModel.resetPasswordFlow,<br>            onRegisterNow = { navHostController.navigate(NavigationGraph.RegisterScreen.route) },<br>            onForgotPassword = { email -&gt; loginViewModel.resetPassword(email) },<br>            onLogin = { email, password -&gt; loginViewModel.login(email, password) },<br>            loginSuccess = { navHostController.navigate(NavigationGraph.HomeScreen.route) { popUpTo(0) } }<br>        )<br>    }<br>}<br><br>@Composable<br>fun Content(<br>    paddingValues: PaddingValues,<br>    signInStateFlow: MutableSharedFlow&lt;Response&lt;AuthResult&gt;&gt;,<br>    resetPasswordStateFlow: MutableSharedFlow&lt;Response&lt;Void?&gt;&gt;,<br>    onRegisterNow: () -&gt; Unit,<br>    onForgotPassword: (String) -&gt; Unit,<br>    onLogin: (String, String) -&gt; Unit,<br>    loginSuccess: () -&gt; Unit,<br>    hostState: SnackbarHostState<br>) {<br>    val emailText = remember {<br>        mutableStateOf(&quot;&quot;)<br>    }<br>    val passwordText = remember {<br>        mutableStateOf(&quot;&quot;)<br>    }<br>    var showForgotPasswordDialog by remember {<br>        mutableStateOf(false)<br>    }<br>    val scope = rememberCoroutineScope()<br><br>    if (showForgotPasswordDialog)<br>        MyAlertDialog(<br>            onDismissRequest = { showForgotPasswordDialog = false },<br>            onConfirmation = {<br>                if (emailText.value != &quot;&quot;) {<br>                    onForgotPassword(emailText.value)<br>                    showForgotPasswordDialog = false<br>                } else {<br>                    scope.launch {<br>                        hostState.showSnackbar(&quot;Please enter email address&quot;)<br>                    }<br>                }<br>            },<br>            title = &quot;Forgot Password?&quot;,<br>            text = &quot;Send a password reset email to entered email address.&quot;,<br>            confirmButtonText = &quot;Send&quot;,<br>            dismissButtonText = &quot;Cancel&quot;,<br>            cancelable = true<br>        )<br><br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(paddingValues)<br>    ) {<br>        Text(<br>            text = &quot;Login&quot;,<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .padding(start = 25.dp, end = 20.dp, top = 20.dp),<br>            style = MaterialTheme.typography.displayMedium,<br>            fontWeight = FontWeight.SemiBold<br>        )<br>        Text(<br>            text = &quot;Please sign in to continue.&quot;,<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .padding(start = 25.dp, end = 20.dp, top = 5.dp),<br>            style = MaterialTheme.typography.bodyLarge<br>        )<br>        TextField(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .wrapContentHeight()<br>                .padding(start = 20.dp, end = 20.dp, top = 40.dp),<br>            singleLine = true,<br>            value = emailText.value,<br>            onValueChange = { text -&gt; emailText.value = text },<br>            label = { Text(&quot;Email&quot;) },<br>            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),<br>            leadingIcon = { Icon(Icons.Filled.Email, &quot;email&quot;) }<br>        )<br>        TextField(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .wrapContentHeight()<br>                .padding(20.dp),<br>            singleLine = true,<br>            value = passwordText.value,<br>            onValueChange = { text -&gt; passwordText.value = text },<br>            label = { Text(&quot;Password&quot;) },<br>            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),<br>            visualTransformation = PasswordVisualTransformation(),<br>            leadingIcon = { Icon(Icons.Filled.Lock, &quot;password&quot;) }<br>        )<br>        Button(<br>            onClick = {<br>                onLogin(emailText.value, passwordText.value)<br>            },<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .wrapContentHeight()<br>                .padding(start = 20.dp, end = 20.dp, top = 20.dp),<br>            content = { Text(text = &quot;Login&quot;) }<br>        )<br>        Text(<br>            color = MaterialTheme.colorScheme.primary,<br>            text = &quot;Forgot Password?&quot;,<br>            modifier = Modifier<br>                .wrapContentWidth()<br>                .wrapContentHeight()<br>                .align(alignment = Alignment.CenterHorizontally)<br>                .padding(start = 20.dp, end = 20.dp, top = 10.dp)<br>                .clickable { showForgotPasswordDialog = true },<br>            style = MaterialTheme.typography.titleMedium<br>        )<br>        Spacer(modifier = Modifier.weight(1f))<br>        Text(<br>            text = buildAnnotatedString {<br>                append(&quot;Don&#39;t have an account?&quot;)<br>                withStyle(style = SpanStyle(MaterialTheme.colorScheme.primary)) { append(&quot; Register now&quot;) }<br>            },<br>            modifier = Modifier<br>                .wrapContentWidth()<br>                .wrapContentHeight()<br>                .align(alignment = Alignment.CenterHorizontally)<br>                .padding(20.dp)<br>                .clickable { onRegisterNow() },<br>            style = MaterialTheme.typography.titleMedium<br>        )<br>    }<br>    LoginInState(<br>        flow = signInStateFlow,<br>        onSuccess = { loginSuccess() },<br>        onError = { scope.launch { hostState.showSnackbar(&quot;The email address or password is incorrect&quot;) } }<br>    )<br>    ResetPasswordState(<br>        flow = resetPasswordStateFlow,<br>        onSuccess = { scope.launch { hostState.showSnackbar(&quot;Email sent successfully, check your inbox&quot;) } },<br>        onError = { scope.launch { hostState.showSnackbar(&quot;Oops! something went wrong, try again&quot;) } }<br>    )<br>}<br><br>@Composable<br>fun LoginInState(<br>    flow: MutableSharedFlow&lt;Response&lt;AuthResult&gt;&gt;,<br>    onSuccess: () -&gt; Unit,<br>    onError: () -&gt; Unit<br>) {<br>    val isLoading = remember { mutableStateOf(false) }<br>    if (isLoading.value) MyCircularProgress()<br>    LaunchedEffect(Unit) {<br>        flow.collect {<br>            when (it) {<br>                is Response.Loading -&gt; {<br>                    Log.i(&quot;Login state -&gt; &quot;, &quot;Loading&quot;)<br>                    isLoading.value = true<br>                }<br><br>                is Response.Error -&gt; {<br>                    Log.e(&quot;Login state -&gt; &quot;, it.message)<br>                    isLoading.value = false<br>                    onError()<br>                }<br><br>                is Response.Success -&gt; {<br>                    Log.i(&quot;Login state -&gt; &quot;, &quot;Success&quot;)<br>                    isLoading.value = false<br>                    onSuccess()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun ResetPasswordState(<br>    flow: MutableSharedFlow&lt;Response&lt;Void?&gt;&gt;,<br>    onSuccess: () -&gt; Unit,<br>    onError: () -&gt; Unit<br>) {<br>    val isLoading = remember { mutableStateOf(false) }<br>    if (isLoading.value) MyCircularProgress()<br>    LaunchedEffect(Unit) {<br>        flow.collect {<br>            when (it) {<br>                is Response.Loading -&gt; {<br>                    Log.i(&quot;Reset password state -&gt; &quot;, &quot;Loading&quot;)<br>                    isLoading.value = true<br>                }<br><br>                is Response.Error -&gt; {<br>                    Log.e(&quot;Reset password state -&gt; &quot;, it.message)<br>                    isLoading.value = false<br>                    onError()<br>                }<br><br>                is Response.Success -&gt; {<br>                    Log.i(&quot;Reset password state -&gt; &quot;, &quot;Success&quot;)<br>                    isLoading.value = false<br>                    onSuccess()<br>                }<br>            }<br>        }<br>    }<br>}</pre><pre>@HiltViewModel<br>class LoginViewModel @Inject constructor(<br>    private val loginUseCase: LoginUseCase,<br>    private val resetPasswordUseCase: ResetPasswordUseCase<br>) : ViewModel() {<br><br>    private val _loginFlow = MutableSharedFlow&lt;Response&lt;AuthResult&gt;&gt;()<br>    val loginFlow = _loginFlow<br><br>    private val _resetPasswordFlow = MutableSharedFlow&lt;Response&lt;Void?&gt;&gt;()<br>    val resetPasswordFlow = _resetPasswordFlow<br><br>    fun login(email: String, password: String) = viewModelScope.launch {<br>        loginUseCase.invoke(email, password).collect { response -&gt;<br>            _loginFlow.emit(response)<br>        }<br>    }<br><br>    fun resetPassword(email: String) = viewModelScope.launch {<br>        resetPasswordUseCase.invoke(email).collect { response -&gt;<br>            _resetPasswordFlow.emit(response)<br>        }<br>    }<br><br>}</pre><p>Create <em>RegisterScreen </em>and <em>RegisterViewModel </em>classes under <em>presentation/screen/register</em> package</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun RegisterScreen(<br>    navHostController: NavHostController,<br>    registerViewModel: RegisterViewModel = hiltViewModel()<br>) {<br>    val scope = rememberCoroutineScope()<br>    val hostState = remember { SnackbarHostState() }<br><br>    Scaffold(<br>        modifier = Modifier.fillMaxSize(),<br>        snackbarHost = { SnackbarHost(hostState = hostState) },<br>        topBar = {<br>            TopAppBar(<br>                title = { Text(text = &quot;Register&quot;) },<br>                navigationIcon = {<br>                    IconButton(<br>                        onClick = { navHostController.popBackStack() }<br>                    ) {<br>                        Icon(<br>                            imageVector = Icons.Filled.ArrowBack,<br>                            contentDescription = &quot;back button&quot;<br>                        )<br>                    }<br>                }<br>            )<br>        }<br>    ) { paddingValues -&gt;<br>        Content(<br>            paddingValues = paddingValues,<br>            registerFlowState = registerViewModel.registerFlow,<br>            onNavigateToLogin = { navHostController.popBackStack() },<br>            onRegister = { email, password -&gt; registerViewModel.register(email, password) },<br>            registerSuccess = { navHostController.navigate(NavigationGraph.HomeScreen.route) },<br>            registerError = { scope.launch { hostState.showSnackbar(&quot;Oops! something went wrong, check your connection and try again&quot;) } }<br>        )<br>    }<br>}<br><br>@Composable<br>fun Content(<br>    paddingValues: PaddingValues,<br>    registerFlowState: MutableSharedFlow&lt;Response&lt;AuthResult&gt;&gt;,<br>    onRegister: (String, String) -&gt; Unit,<br>    onNavigateToLogin: () -&gt; Unit,<br>    registerSuccess: () -&gt; Unit,<br>    registerError: () -&gt; Unit<br>) {<br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(paddingValues)<br>    ) {<br>        val emailText = remember {<br>            mutableStateOf(&quot;&quot;)<br>        }<br>        val passwordText = remember {<br>            mutableStateOf(&quot;&quot;)<br>        }<br><br>        TextField(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .wrapContentHeight()<br>                .padding(start = 20.dp, end = 20.dp, top = 5.dp),<br>            value = emailText.value,<br>            onValueChange = { text -&gt; emailText.value = text },<br>            label = { Text(&quot;Email&quot;) },<br>            singleLine = true,<br>            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),<br>            leadingIcon = { Icon(Icons.Filled.Email, &quot;email&quot;) },<br>        )<br>        TextField(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .wrapContentHeight()<br>                .padding(20.dp),<br>            value = passwordText.value,<br>            onValueChange = { text -&gt; passwordText.value = text },<br>            label = { Text(&quot;Password&quot;) },<br>            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),<br>            visualTransformation = PasswordVisualTransformation(),<br>            singleLine = true,<br>            leadingIcon = { Icon(Icons.Filled.Lock, &quot;password&quot;) },<br>        )<br>        Button(<br>            onClick = { onRegister(emailText.value, passwordText.value) },<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .wrapContentHeight()<br>                .padding(start = 20.dp, end = 20.dp, top = 20.dp),<br>            content = { Text(text = &quot;Register&quot;) }<br>        )<br>        Spacer(modifier = Modifier.weight(1f))<br>        Text(<br>            style = MaterialTheme.typography.titleMedium,<br>            text = buildAnnotatedString {<br>                append(&quot;Already have an account?&quot;)<br>                withStyle(style = SpanStyle(MaterialTheme.colorScheme.primary)) { append(&quot; Login&quot;) }<br>            },<br>            modifier = Modifier<br>                .wrapContentWidth()<br>                .wrapContentHeight()<br>                .align(alignment = Alignment.CenterHorizontally)<br>                .padding(20.dp)<br>                .clickable { onNavigateToLogin() }<br>        )<br>    }<br>    RegisterState(<br>        registerFlowState = registerFlowState,<br>        onSuccess = { registerSuccess() },<br>        onError = { registerError() }<br>    )<br>}<br><br>@Composable<br>fun RegisterState(<br>    registerFlowState: MutableSharedFlow&lt;Response&lt;AuthResult&gt;&gt;,<br>    onSuccess: () -&gt; Unit,<br>    onError: () -&gt; Unit<br>) {<br>    val isLoading = remember { mutableStateOf(false) }<br>    if (isLoading.value) MyCircularProgress()<br>    LaunchedEffect(Unit) {<br>        registerFlowState.collect {<br>            when (it) {<br>                is Response.Loading -&gt; {<br>                    Log.i(&quot;Register state -&gt; &quot;, &quot;Loading&quot;)<br>                    isLoading.value = true<br>                }<br><br>                is Response.Error -&gt; {<br>                    Log.e(&quot;Register state -&gt; &quot;, it.message)<br>                    isLoading.value = false<br>                    onError()<br>                }<br><br>                is Response.Success -&gt; {<br>                    Log.i(&quot;Register state -&gt; &quot;, &quot;Success&quot;)<br>                    isLoading.value = false<br>                    onSuccess()<br>                }<br>            }<br>        }<br>    }<br>}</pre><pre>@HiltViewModel<br>class RegisterViewModel @Inject constructor(<br>    private val registerUseCase: RegisterUseCase<br>) : ViewModel() {<br><br>    private var _registerFlow = MutableSharedFlow&lt;Response&lt;AuthResult&gt;&gt;()<br>    val registerFlow = _registerFlow<br><br>    fun register(email: String, password: String) = viewModelScope.launch {<br>        registerUseCase.invoke(email, password).collect {<br>            _registerFlow.emit(it)<br>        }<br>    }<br><br>}</pre><p>Setup navigation. Create <em>AuthenticationNavigationViewModel</em>, <em>NavigationGraph </em>and <em>NavigationHelper </em>classes under <em>presentation/navigation</em> package.</p><pre>sealed class NavigationGraph(val route: String) {<br>    data object LoginScreen : NavigationGraph(route = &quot;login_screen&quot;)<br>    data object RegisterScreen : NavigationGraph(route = &quot;register_screen&quot;)<br>    data object HomeScreen : NavigationGraph(route = &quot;home_screen&quot;)<br>}</pre><pre>@Composable<br>fun SetUpNavigationGraph(<br>    navHostController: NavHostController = rememberNavController(),<br>    authenticationNavigationViewModel: AuthenticationNavigationViewModel = hiltViewModel()<br>) {<br>    NavHost(<br>        navController = navHostController,<br>        startDestination = if (authenticationNavigationViewModel.isLoggedInState.value)<br>            NavigationGraph.LoginScreen.route<br>        else<br>            NavigationGraph.HomeScreen.route<br>    ) {<br>        composable(<br>            route = NavigationGraph.HomeScreen.route<br>        ) {<br>            HomeScreen(navHostController = navHostController)<br>        }<br>        composable(<br>            route = NavigationGraph.LoginScreen.route<br>        ) {<br>            LoginScreen(navHostController)<br>        }<br>        composable(<br>            route = NavigationGraph.RegisterScreen.route<br>        ) {<br>            RegisterScreen(navHostController)<br>        }<br>    }<br>}</pre><pre>@HiltViewModel<br>class AuthenticationNavigationViewModel @Inject constructor(<br>    private val isLoggedInUseCase: IsLoggedInUseCase<br>) : ViewModel() {<br><br>    private var _isLoggedInState = mutableStateOf(false)<br>    val isLoggedInState = _isLoggedInState<br><br>    init {<br>        isLoggedIn()<br>    }<br><br>    private fun isLoggedIn() = viewModelScope.launch {<br>        isLoggedInUseCase.invoke().collect {<br>            _isLoggedInState.value = it<br>        }<br>    }<br><br>}</pre><p>Finally update <em>MainActivity </em>class</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            AuthTheme {<br>                // A surface container using the &#39;background&#39; color from the theme<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    SetUpNavigationGraph()<br>                }<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENkvuA5Ud-tdrPCmlKf8-Q.png" /></figure><h3>Overall</h3><p>The provided step-by-step guide outlines the process of creating a Jetpack Compose project with Firebase authentication in Android development. Initially, the guide sets up the project environment by adding necessary dependencies for Google services, Firebase authentication, Dagger Hilt for dependency injection, and Navigation components. Following this, it connects the project to Firebase and enables the Email/Password authentication provider. The subsequent steps involve coding various components, including the core Response class for handling asynchronous responses, the AuthenticationRepository interface defining authentication methods, and its implementation class, AuthenticationRepositoryImpl, utilizing Firebase authentication functionalities. Additionally, the guide covers setting up Dagger Hilt for dependency injection, creating use cases for authentication operations, defining common UI elements like dialogs and progress indicators, and implementing screens for login, registration, and home functionalities using Jetpack Compose. Finally, it establishes navigation between screens using Navigation Graphs and ViewModels, ensuring a seamless user experience.</p><h3><strong>Happy coding.</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=962ee766bed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theme Customization in Android with Jetpack Compose]]></title>
            <link>https://medium.com/@srkan/theme-customization-in-android-with-jetpack-compose-2c36c78c7f7e?source=rss-3bf919b049c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c36c78c7f7e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Serkan]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 20:08:54 GMT</pubDate>
            <atom:updated>2024-02-22T20:08:54.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2K_E94HCMWLfITqtJjcHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXGnON6WhTUXwi2tQi3Gwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2vqzbyGirOPM77102AxmQ.png" /></figure><p>In the dynamic landscape of Android app development, providing users with the ability to personalize their experience is key to creating engaging and user-friendly applications. One crucial aspect of customization is theme management, allowing users to tailor the visual appearance of the app to their preferences. In this article, we’ll explore how to master theme customization using Jetpack Compose and Kotlin.</p><h4><strong>Step-by-Step Guide:</strong></h4><p><strong>Step 1:</strong> Add the following dependencies:</p><p>// Preferences DataStore<br><em>implementation(“androidx.datastore:datastore-preferences:1.0.0”)</em></p><p>// Navigation<br><em>implementation(“androidx.navigation:navigation-compose:2.7.7”)</em><br><em>implementation(“androidx.hilt:hilt-navigation-compose:1.1.0”)</em></p><p><strong>Step 2:</strong> Creating DataStoreUtils for Theme Management</p><p><strong>Step 3:</strong> Designing the Settings screen</p><p><strong>Step 4:</strong> Setting up Navigation and Applying Themes Globally in MainActivity</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a7c326e1ca62fa28b0fc3a68fee20ba/href">https://medium.com/media/4a7c326e1ca62fa28b0fc3a68fee20ba/href</a></iframe><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c36c78c7f7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>